This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there a java equivalent of the python eval function?
There is a String, something like String str = "if a[0]=1 & a[1]=2". How to use this string in a real IF THEN expression? E.g.:
for (Integer[] a : myNumbers) {
if a[0]=1 & a[1]=2 { // Here I'd like to use the expression from str
//...
}
}
Java isn't a scripting language that supports dynamic evaluation (although it does support script execution). I would challenge you to check to see if what you're attempting to do is being done in the right way within Java.
There are two common ways you can approach this, listed below. However they have a significant performance impact when it comes to the runtime of your application.
Script Execution
You could fire up a ScriptEngine, build a ScriptContext, execute the fragment in Javascript or some other language, and then read the result of the evaluation.
http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/
Parsing
You could build a lexical parser that analyses the string and converts that into the operations you want to perform. In Java I would recommend you look at JFlex.
http://www.javaworld.com/javaworld/jw-01-1997/jw-01-indepth.html
http://en.wikipedia.org/wiki/Lexical_analysis
http://jflex.de/
I don't think you can do what you're asking.
Also your java doesn't seem to make much sense. Something like this would make more sense:
for (Integer a : myNumbers) {
if (a.equals(Integer.valueOf(1))){
//...
}
}
You can however say:
if("hello".equals("world")){
//...
}
And you can build a string:
String str = "if "+a[0]+"=1 & "+a[1]+"=2"
And you can put that together and say:
String str = "if "+a[0]+"=1 & "+a[1]+"=2"
if(str.equals("if 1=1 & 2=2")){
//...
}
But I think you're probably just trying to do something the wrong way
Related
This question already has answers here:
How to write a ternary operator (aka if) expression without repeating yourself
(17 answers)
Is using Optional.ofNullable as a replacement for the ternary operator a good practice?
(6 answers)
Avoid violation of DRY with ternary?
(2 answers)
Closed 2 years ago.
I'm fairly new to Java and I'm trying to check if a variable is null and use its value if its not. Previous developer wrote something like this:
xModel.setName(xService.getName(xID) != null ? xService.getName(xID) : "");
And I would like to refactor it so I wouldn't have to use xService twice to just get the name.
I know I can store the value beforehand but this is just an example. I just wonder if there is a way to do this in Java?
Thanks.
I disagree with all other answers. They require special functionality from specific versions by importing structures from the standard library, or obscure calls that works in this specific case, and all in all just hides the simplicity of what you're trying to do.
Keep it simple (KISS). Don't introduce more complexity and concepts when you don't need them. You're refactoring another developers code, which means this is a project where someone else will probably be reading your code later on. So keep it dead simple.
String name = xService.getName(xID);
xModel.setName(name != null ? name : "");
This is more readable than all other examples and doesn't require intimate knowledge of the standard library and its API.
Objects.toString​( Object o, String nullDefault )
In this particular case you can use java.util.Objects.toString. Second argument is a default value to use in case of a null in the first argument.
xModel.setName(Objects.toString(xService.getName(x.ID), ""));
What you have is already the best core Java can do pre Java 8. From 8 onwards, you may use optionals:
xModel.setName(Optional.ofNullable(xService.getName(xID)).orElse(""));
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm just getting started with Java and while reading through this guide I noticed the following snippet, describing a recent update to the Junit framework.
We can now write assertion messages in a lambda in JUnit 5, allowing
the lazy evaluation to skip complex message construction until needed:
#Test
public void shouldFailBecauseTheNumbersAreNotEqual_lazyEvaluation() {
Assertions.assertTrue(
2 == 3,
() -> "Numbers " + 2 + " and " + 3 + " are not equal!");
}
As someone new to Java this feels like a large implementation just to get around string concatenation.
Are evaluating strings in Java really that slow (relative to other languages?). How does it compare to other compiled languages like C, Golang, etc..?
The point is: there is no lazy string formatting in Java.
Meaning, in languages like C you might see things such as:
#define debug_print...
( see some real world examples here )
The idea is to define a macro to which you pass a complicated string. But the compiler makes sure that code gets only generated for situations that actually that string to be present.
Meaning: when using debug_print(), that complicated string concat that is might be required to build the messages passed to the macro call only happens when the message is really needed! The message is concatenated lazily.
In Java, we simply have no way to express that. You always have to go
if (someCondition) {
then pull together that large string
which isn't nice, especially when doing it for tracing. Some people in our group write that code, and it is just overly annoying that each and any trace statement has that leading if statement. That renders your whole code much less readable.
Therefore: this is not at all about the cost of string concats. It is about only spending the required CPU cycles if that string is truly needed.
And to answer the actual question: in the end, when that code gets invoked often enough, the JIT will turn it into carefully optimized machine code anyway. Thus: the actual string concat is not the issue.
In other words: you don't think of "performance" for Java in terms of source code. What matters is what happens at runtime, by the JIT.
Here's the bottom line. Starting out in Java, don't worry about minor performance issues like String concatenation. It may be a small issue for a large application server where lots of String concatenation is done but the results are not used. An example would be logging, where the log level of causes the event to be ignored. Also, Java uses a StringBuilder to concatenate a series of literals separated by the "+' operator, which is reasonably performant.
This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 6 years ago.
i have a string with a math function, like "35+20". i want a new double variable that takes in the result of the math function i.e, 55.0 How do i achieve this? this is actually for android, i'm making a calculator..
Manually parse the string and do a calculation at each operator symbol. It will get more complicated when dealing with brackets, however.
If you want to write it yourself, you'll probably want to implement the Shunting Yard Algorithm.
There are also some libraries that handle it for you.
https://github.com/uklimaschewski/EvalEx
Since you have mentioned you are working on a calculator I am assuming that you might not only be interested in just the + operation but on a bunch of other stuffs too.
You can look in to open source GitHub project linked below which provides the JAVA implementation for the stuff you are trying to do https://github.com/uklimaschewski/EvalEx
which can give you a good set of functionality that you desire.
This project takes in a string as an expression and the returns the result in BigDecimal format.
You can always extend it and tweek it to custom suite you needs.
This question already has answers here:
Method for evaluating math expressions in Java
(8 answers)
Closed 9 years ago.
I tried searching for it via google and here but I'm not finding questions to what I mean (search engines don't understand the context by which I mean function).
Essentially I want to do the following
double f(String function, double a){
return function.Function(a);
}
What would happen is the string function is of the form "x^2+2" it would likely be converted somehow to "x.pow(2) + 2" and then x is replaced by a and the result of the function is returned.
Is there any Java class or method that does what I said (or simple way to do it)? Or any code from another source that does what I said or a variant.
I don't have to code what I said, I just need f(x) to solve root finding problems for any function string passed as input. I thought Java would have such a method somewhere but I can't find it.
So, in Java you have an essential problem because you cannot directly convert a String to a mathematical expression. Your options are as follows:
Search for a library that can convert a particularly formatted string to a mathematical expression.
Parse the string yourself. String parsing is difficult and error prone, and the Java around this would be difficult.
Use Scala, which would allow you to directly compose functions to pass into your function, rather than trying to do the expensive conversion from a human-readable string to a machine-interpretable function. Note that Scala is interoperable with Java, but has a bit of a learning curve. Other functional languages can handle this as well, but may lack interoperability.
This question already has answers here:
How to format strings in Java
(10 answers)
Closed 5 years ago.
Is there a more elegant way of doing this in Java?
String value1 = "Testing";
String test = "text goes here " + value1 + " more text";
Is it possible to put the variable directly in the string and have its value evaluated?
String test = String.format("test goes here %s more text", "Testing");
is the closest thing that you could write in Java
A more elegant way might be:
String value = "Testing";
String template = "text goes here %s more text";
String result = String.format(template, value);
Or alternatively using MessageFormat:
String template = "text goes here {0} more text";
String result = MessageFormat.format(template, value);
Note, if you're doing this for logging, then you can avoid the cost of performing this when the log line would be below the threshold. For example with SLFJ:
The following two lines will yield the exact same output. However, the second form will outperform the first form by a factor of at least 30, in case of a disabled logging statement.
logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);
Rythm a java template engine now released with an new feature called String interpolation mode which allows you do something like:
String result = Rythm.render("Hello #who!", "world");
The above case shows you can pass argument to template by position. Rythm also allows you to pass arguments by name:
Map<String, Object> args = new HashMap<String, Object>();
args.put("title", "Mr.");
args.put("name", "John");
String result = Rythm.render("Hello #title #name", args);
Links:
Check the full featured demonstration
read a brief introduction to Rythm
download the latest package or
fork it
It may be done by some template-libaries. But beware, Strings are immutable in Java. So in every case at some low level the concatenation will be done.
You'll always have to use some form of concatenation for this (assuming value1 isn't a constant like you show here).
The way you've written it will implicitly construct a StringBuilder and use it to concatenate the strings. Another method is String.format(String, Object...)1, which is analogous to sprintf from C. But even with format(), you can't avoid concatenation.
1 Yes, I know the anchor link is broken.
What you want is called String interpolation. It is not possible in Java, although JRuby, Groovy and probably other JVM languages do that.
Edit: as for elegance, you can use a StringBuffer or check the other poster's solution. But at the low level, this will always be concatenation, as the other posters said.
You can use this free library. It gives you sprintf like functionality. Or use String.format static method provided you use Java 5 or newer.
Why do you think string concatenation isn't elegant?
If all you are doing is simple concatenation, I'd argue that code readability is more important and I'd leave it like you have it. It's more readable than using a StringBuilder.
Performance won't be the problem that most people think it is.
Read this from CodingHorror
I would use a StringBuffer.. it's a common practise when you are dealing with strings. It may seem a bit when you see it for the first time, but you'll get quickly used to it..
String test = new StringBuffer("text goes here ").append(value1).append(" more text").toString();
Strings are immutable thus a new instance is created after every concatenation. This can cause performance issues when used in loops.
StringBuffer is mutable version of String - that means you can create one, modify it as you want and you have still only one instance. When desired you can get a String representation of the StringBuffer by calling it's toString() method.
The problem is not if this is an elegant way or not. The idea behind using a template system may be that you put your template in a normal text file and don't have to change java code if you change your message (or think about i18ln).