Can I make expressions in Java and store them into a variable of Boolean datatype? So that I can use them in conditional use? If so please tell how.
Expressions like:
(temp.name(0) && temp.name(1))
and save them into a variable which can either be true or false.
Asked
Active
Viewed 1,287 times
-4

Makyen
- 31,849
- 12
- 86
- 121

Shariq Alee
- 35
- 6
-
Possible duplicate of [Is there an eval() function in Java?](http://stackoverflow.com/questions/2605032/is-there-an-eval-function-in-java) – ryanyuyu Jan 09 '15 at 20:20
2 Answers
2
Expressions themselves cannot be saved as a variable to be reused (like a function). You can do one of a few things:
1) Store the value of an expression
boolean nameValid = name.length() >= 1;
2) Define a method
public boolean isNameValid(String name) {
return name != null && name.length() >= 1;
}
-
1There are some scripting api can be used to parse the expressions. It is not impossible. – kosa Jan 09 '15 at 20:40
-
Yes, good call. However, I didn't include that because I felt that wasn't the intent of the question. But yeah, there are, and they do work if you need that sort of thing. – Todd Jan 09 '15 at 20:41
0
You can use this approach if the condition execution time is very high, so you want to only calculate one time and store the result to use it after that many times. Thus, you save your time from repeating the calculation.
Example:
if (veryLongCalc() || someCond) {
if (veryLongCalc()) {
// veryLongCalc() will be called here 2 times
} else { // someCond == true
}
}
Can be better:
boolean b = veryLongCalc();
if (b || someCond) {
if (b) {
// veryLongCalc() only called once !!
} else {
}
}