java how to determine logical expression minimum values to evauate - java

I have an expression (an example)
(value1<15 AND value2>25) OR ((value3>0 and vaue4<5) OR (value5<6 and value7>8))
The issue is value1-7 are calls to external services, which are expensive. And we need to reduce cost, so we need to make a minimum number of calls to evaluate this expression. For example if we have
(value1<15 AND value2>25)
evaluated to true, we don't need to evaluate right part, so we don't need to make useless calls to external services. How to determine in java (or may be just in math) when we need to stop, and further evaluations will not make any effect?
UPDATE
I have 5 workers that works on 5 different servers.
first worker:
accept(expression)
value1=calculateValue1()
setValueToExpression(expression, 0, value1)
enough=expression.checkIsItEnough()
if(!enough){
determineNextWorker(expression)
sendToNExtWorker()
}
else return expression.evaluate()
The second worker
accept(expression)
value2=calculateValue2()
setValueToExpression(expression, 1, value2)
enough=expression.checkIsItEnough()
if(!enough){
determineNextWorker(expression)
sendToNextWorker()
}
else return expression.evaluate()
.....................
As I said in comments, I clearly understand that if we can write
evaluator.evaluate("(value1<5 and value2>6) or (value3>5 and value4>7)")
it evaluates it as all of us know, but I don't have this ability due to many reasons. I also can't make it function calls value1()<15...
It's happening synchronously, one by one but even on different servers, kinda offline evaluation. Hope it's clear

Consider normal short-circuit intermediate code for:
(value1<15 AND value2>25) OR ((value3>0 and value4<5) OR (value5<6 and value7>8))
if value1<15 goto value2_test else goto value3_test
value2_test:
if value2>25 goto success else goto value3_test
value3_test:
if value3>0 goto value4_test else goto value5_test
value4_test:
if value4<5 goto success else goto value5_test
value5_test:
if value5<6 goto value7_test else goto fail
value7_test:
if value7>8 goto success else goto fail
You could simplify things substantially by having a tree representation of your expression, and passing around subexpressions represented by trees rather than the whole expression.
For example, the first worker would have two subexpressions: value2>25 and (value3>0 and value4<5) OR (value5<6 and value7>8). Select the first one if the test succeeds, the second one if it fails.
The value2>25 worker would have two subexpressions: "success" and (value3>0 and value4<5) OR (value5<6 and value7>8)
I am not aware of any library to do the conversions. If it exists, it would be in the domain of compiler construction.
I would try very hard to change this to something where one worker could organize the job, and simply call on other workers to evaluate one relational condition.
========================================================================
More detail, because this seems to be the sort of answer the OP is looking for:
Terminology:
"term" -> A comparison or Boolean variable, such as value2>25
"product" -> The AND of some Boolean expressions
"sum" -> The OR of
some Boolean expressions.
Consider only sum-of-products expressions, such as (value1<15 AND value2>25) OR ((value3>0 and value4<5) OR (value5<6 and value7>8)). This is not a very significant limitation. Many optimizations and simplifications used in digital logic design depend on converting arbitrary logical expressions to sum-of-products.
At each step, the worker for the leading term of an expression is called. Depending on the expression and the outcome of its test, it can declare success, declare failure, or calculate a new expression that must be passed to the worker for its leading term.
if this worker's condition is true
if more terms in current product
remove the leading term from the current product
pass the new expression to the worker for the next term
else
declare success
else
if there is another product
remove the leading product from the expression
pass the new expression to the worker for the new leading product's leading term
else
declare failure

A standard condition will work that way (short circuit) because it will only evaluate the expressions if necessary (if the first part of an || condition is true it won't evaluate the rest):
if ((value1() < 15 && value2() > 25) || (value3() > 0 && vaue4() < 5) ...)
Note that I have replace the values by method calls - if you precalculate each value of course it won't work...
Examples:
if your condition value1() < 15 returns false, then value2() won't be called
if the first condition value1() < 15 && value2() > 25 is true, value3() and value4() won't be evaluated.
References:
See JLS #15.23 (emphasis mine):
The conditional-and operator && is like &, but evaluates its right-hand operand only if the value of its left-hand operand is true.
Similarly in JLS #15.24:
The conditional-or operator || operator is like |, but evaluates its right-hand operand only if the value of its left-hand operand is false.

Conditional logic by default evaluates the least amount of conditions needed to obtain an evaluation result. This is not specific to Java. This is how things work. Also, the grouping parentheses are completely optional in your case.
Depending on your use case, you may want to push forward inside the condition the expressions that are most likely to be true. And perhaps consider caching for a certain amount of time some of the results, if applicable.

Related

How do you write a boolean statement [duplicate]

I have been working with Java a couple of years, but up until recently I haven't run across this construct:
int count = isHere ? getHereCount(index) : getAwayCount(index);
This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.
if isHere is true, getHereCount() is called,
if isHere is false getAwayCount() is called.
Correct? What is this construct called?
Yes, it is a shorthand form of
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.
The official name is given in the Java Language Specification:
§15.25 Conditional Operator ? :
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:
if (someBool)
doSomething();
else
doSomethingElse();
into this:
someBool ? doSomething() : doSomethingElse();
Simple words:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
Others have answered this to reasonable extent, but often with the name "ternary operator".
Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.
According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
condition ? truth : false;
If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.
It is called the Conditional Operator and it is a type of Ternary Operation.
int count = isHere ? getHereCount(index) : getAwayCount(index);
means :
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
Not exactly correct, to be precise:
if isHere is true, the result of getHereCount() is returned
otheriwse the result of getAwayCount() is returned
That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.
Also, it's not exactly syntactically equivalent to the if-else version. For example:
String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;
If coded with if-else will always result in more bytecode.
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
public class Foo {
final double value;
public Foo(boolean positive, double value) {
this.value = positive ? value : -value;
}
}
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
This construct is called Ternary Operator in Computer Science and Programing techniques. And Wikipedia suggest the following explanation:
In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.
Not only in Java, this syntax is available within PHP, Objective-C too.
In the following link it gives the following explanation, which is quiet good to understand it:
A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.
In Perl/PHP it works as: boolean_condition ? true_value : false_value
In C/C++ it works as: logical expression ? action for true : action for false
This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.
We can simplify the If-Else blocks with this Ternary operator for one code statement line.For Example:
if ( car.isStarted() ) {
car.goForward();
} else {
car.startTheEngine();
}
Might be equal to the following:
( car.isStarted() ) ? car.goForward() : car.startTheEngine();
So if we refer to your statement:
int count = isHere ? getHereCount(index) : getAwayCount(index);
It is actually the 100% equivalent of the following If-Else block:
int count;
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
That's it!
Hope this was helpful to somebody!
Cheers!
Correct. It's called the ternary operator. Some also call it the conditional operator.
Its Ternary Operator(?:)
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison.
Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:
String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";
which is better than using if, else if, else.
?: is a Ternary Java Operator.
Its syntax is:
condition ? expression1 : expression2;
Here, the condition is evaluated and
condition returns true, the expression1 will execute.
condition returns false, the expression2 will execute.
public class Sonycode {
public static void main(String[] args) {
double marks = 90;
String result = (marks > 40) ? "passed in exam" : "failed in exam";
System.out.println("Your result is : " + result);
}
}
Output :-
Your result is : passed in exam
It's the conditional operator, and it's more than just a concise way of writing if statements.
Since it is an expression that returns a value it can be used as part of other expressions.
Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.
Ternary Conditional Operator
I happen to really like this operator, but the reader should be taken into consideration.
You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.
First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.
Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:
callMethodWhatever(Long + Expression + with + syntax) if conditional
If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.
The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.
When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.
Conditional expressions are in a completely different style, with no explicit if in the statement.
The syntax is:
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1 if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.
cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127

java for loop with "true" as the stop condition?

I have a program I need to implement that has the following code:
for (int n = 1024; true; n+=n)
I cannot find any other examples of java loops having such a format. What does this mean? I've tried to research it, but I don't even know what to search for - it's totally foreign to me.
The basic for statement is described in the language spec:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
You are asking about the case when Expression is true. (The square brackets above mean it is optional).
The meaning of that is described just below, in Sec 14.14.1.2:
If the Expression is not present, or it is present and the value resulting from its evaluation (including any possible unboxing) is true, then the contained Statement is executed. 
...
If the Expression is present and the value resulting from its evaluation (including any possible unboxing) is false, no further action is taken and the forstatement completes normally.
So, Expression is present, and evaluates to true (because true evaluates to true). Hence, Statement is executed, and will continue to be executed because Expression remains true.
As such, it is an infinite loop (unless there is a break, return, throw or System.exit inside the loop).
Why you dont use another loop? Use for example do-while instead of
for (int n = 1024; true; n+=n)
You can make a work around with:
int n=1024;
do{
//your code
n+=n;
}while(condition==false);

Java & and && operators troubles

I'm trying to figure out why & operator throws an exception and suspends my program but when I use && operator the program works with no errors.
Here is the portion of the code:
books is an arraylist of objects Book.
areYouBook returns true if the book's ISBN I'm looking for matches a.
The method findBook checks if I already have the book in the arraylist. When the method returns null, it means I have to create the book and add it to the ArrayList.
Thank you very much for your help!
public Book findBook(int a){
int i=0;
while((i<(books.size()))&!((books.get(i)).areYouBook(a)))
i++;
if(i<(books.size()))
return books.get(i);
else
return null;
}
I can tell you from here that the difference between the & operator and the && operator is that && will check the first expresion, and if it evaluates to false, then it will simply break from the check, but the & operator will run the following expression regardless of whether or not the first one turned out to be false.
So, the code you have written will check (i<(books.size())), and whether or not that turns out to be false, !((books.get(i)).areYouBook(a)) will still be executed.
If however, you used && and (i<(books.size())) was false, the second part of your check, which is !((books.get(i)).areYouBook(a)), will not be executed.
I hope this helps.
Edit:
You mentioned an error being thrown when you used the & operator instead of the && operator. Since the & operator does run the second expression even if the first one is false, I'm wondering if your second expression is actually throwing an error, and is getting called when you use &.
Edit 2:
Ok. Lets say that books has a size of 12 (indexes 0-11) just for demonstration. So, when you use the & operator, your while loop runs until i is 12. When i is 12, the loop executes (i<(books.size())) (which returns false) and CONTINUES to execute !((books.get(i)).areYouBook(a)). Inside the second expression, books.get(i) is being called, when i is 12. The books list only goes from indexes 0-11, throwing a java.lang.IndexOutOfBoundsException.
java conditional operators says:
the operators && and || exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
the logical AND operator && will be short-cuircuting if the left side condition is false, on the other hand, when the left side condition is false the right side condition is never be executed.
but the bitwise & operator performs a bitwise AND operation.
The logical AND that you're trying to use is represented by the && symbol i.e. True && False resolves to False. The single ampersand "&" represents a bitwise AND i.e. 0101 & 0100 resolves to 0110.

The meaning of ? in a java line [duplicate]

I have been working with Java a couple of years, but up until recently I haven't run across this construct:
int count = isHere ? getHereCount(index) : getAwayCount(index);
This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.
if isHere is true, getHereCount() is called,
if isHere is false getAwayCount() is called.
Correct? What is this construct called?
Yes, it is a shorthand form of
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.
The official name is given in the Java Language Specification:
§15.25 Conditional Operator ? :
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:
if (someBool)
doSomething();
else
doSomethingElse();
into this:
someBool ? doSomething() : doSomethingElse();
Simple words:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
Others have answered this to reasonable extent, but often with the name "ternary operator".
Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.
According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
condition ? truth : false;
If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.
It is called the Conditional Operator and it is a type of Ternary Operation.
int count = isHere ? getHereCount(index) : getAwayCount(index);
means :
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
Not exactly correct, to be precise:
if isHere is true, the result of getHereCount() is returned
otheriwse the result of getAwayCount() is returned
That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.
Also, it's not exactly syntactically equivalent to the if-else version. For example:
String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;
If coded with if-else will always result in more bytecode.
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
public class Foo {
final double value;
public Foo(boolean positive, double value) {
this.value = positive ? value : -value;
}
}
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
This construct is called Ternary Operator in Computer Science and Programing techniques. And Wikipedia suggest the following explanation:
In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.
Not only in Java, this syntax is available within PHP, Objective-C too.
In the following link it gives the following explanation, which is quiet good to understand it:
A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.
In Perl/PHP it works as: boolean_condition ? true_value : false_value
In C/C++ it works as: logical expression ? action for true : action for false
This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.
We can simplify the If-Else blocks with this Ternary operator for one code statement line.For Example:
if ( car.isStarted() ) {
car.goForward();
} else {
car.startTheEngine();
}
Might be equal to the following:
( car.isStarted() ) ? car.goForward() : car.startTheEngine();
So if we refer to your statement:
int count = isHere ? getHereCount(index) : getAwayCount(index);
It is actually the 100% equivalent of the following If-Else block:
int count;
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
That's it!
Hope this was helpful to somebody!
Cheers!
Correct. It's called the ternary operator. Some also call it the conditional operator.
Its Ternary Operator(?:)
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison.
Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:
String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";
which is better than using if, else if, else.
?: is a Ternary Java Operator.
Its syntax is:
condition ? expression1 : expression2;
Here, the condition is evaluated and
condition returns true, the expression1 will execute.
condition returns false, the expression2 will execute.
public class Sonycode {
public static void main(String[] args) {
double marks = 90;
String result = (marks > 40) ? "passed in exam" : "failed in exam";
System.out.println("Your result is : " + result);
}
}
Output :-
Your result is : passed in exam
It's the conditional operator, and it's more than just a concise way of writing if statements.
Since it is an expression that returns a value it can be used as part of other expressions.
Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.
Ternary Conditional Operator
I happen to really like this operator, but the reader should be taken into consideration.
You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.
First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.
Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:
callMethodWhatever(Long + Expression + with + syntax) if conditional
If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.
The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.
When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.
Conditional expressions are in a completely different style, with no explicit if in the statement.
The syntax is:
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1 if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.
cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127

Multiple && Statements - Efficiency [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does Java evaluate remaining conditions after boolean result is known?
When executing code with multiple && statements in java, does the compiler continue to resolve additional boolean comparisons if the first one resolves to false?
if (1==2 && 3==4 && 4==5) { Do Something }
Once determining 1==2 is false, will the compiler immediately break out of the if statement or will it continue to resolve 3==4 and 4==5 after?
In the case of && it'll stop evaluating the moment it detects that one of the conditions is false. This is called short circuit evaluation.
"SHORT CIRCUIT EVALUATION IN PROGRAMMING LANGUAGES"
In the case of any logical expression most compiler stop evaluation expression as soon as result evaluated. its not only in Java but in almost in every language. (but not all e.g. VB6)
You can also check it as follows:
i = 0 , j =1;
i && ++j;
system.out.print(" j=" + j);
The value of j will be 1, it means ++j was not executed.
does the compiler continue to resolve additional boolean comparisons if the first one resolves to false
The short answer. No! The compiler javac and the JIT analyses statically all the code. It doesn't take short cuts like this. e.g. if the second condition doesn't compile, you will always get a compilation error regardless of the first condition.
What you may have intended to ask is; will the program execute the other conditions if the first or second one is false In this case, it will not.
This doesn't make a difference for the compiler -- all it does is resolve the boolean comparisons into machine code, represented by one or more .class files.
As far as the actual runtime... If I remember correctly from Computer Science class, both Tarun's and Lews's answers are correct -- the comparison will short-circuit as soon as it gets to an expression that isn't true.
IF "1==2" is false than the compiler will immediately break out the if statement.
&&
- The above is a short-circuit AND operator. If the 1st condition results in false the 2nd condition is not evaluated.
Eg:
if ((a==false) && (b==true)){
}
The above will stop after the first evaluation.
- If you want to force the evaluation of both the conditions, then try Non-Short Circuit AND (&)
A sidenote to the keyword 'Efficiency' in your title :- as stated by other answers your basic question is easily answered, so it's not a question of efficiency, but a question if you need for some reason all expressions to be evaluated, for example when executing code which changes state (which would be by the way not good coding at all).
But if you think of 'Efficiency' in terms of executing speed, then you almost never have to optimize on that level, either the compiler will do it for you or you wouldn't notice the difference. It may be important in some time critical operation or in operations which run in very big loops, but in nearly every other case, it's much more important to write clean code, so that another human can read it well.

Categories