Parallel Boolean Expression Evaluation in Java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When Java evaluates a conjunction (<boolean exp1> && <boolean exp2>), does it eval exp2 if exp1 is false?
If I have 2 condition say, A and B and I type:
A && B
Are they both evaluated in parallel and only then it does AND?
For example, if I type A && false will it evaluate the A condition or it knows it will be false anyway?
And if it's not done in parallel, does it start from the right or left?
(A && false VS false && A).
Thanks.
EDIT: Got it. Thanks to all!

A && B
no,
A is first evaluated and if A is false it skips evaluating B
if A is true then it checks if B is true
A && false
in this case, A is evaluated first and if A is false, it doesnt check the next condition(false). If A is true then false will be evaluated but as it is false the whole condition would be false.

It will start from left to right. That is if there are no parentheses involved.
if("name".equals(variable1)){}
is will get an error when var1 is null. However, when you use:
if(variable1.equals("name")){}
it is null safe.

Related

Working of short circuit and unary operator

Please have a look at the following code:
int i=5;
boolean b = i<5 && ++i<5;//line 2
System.out.println(i);//line 3, prints 5
In line 2, according to my understanding: Since among all the operators, ++ has highest precedence ++i should be evaluated first. But line 3 actually is printing i=5 (and not 6). Meaning, && has evaluated before ++ operator. How is it possible?
EDIT: From the answers I see that "In Java, all expressions are evaluated from left to right.". But when does actually precedence order comes into play. In following code:
int a=1,b=1,c=1;
boolean b = a==b&&b==c;//Line2
In line2 code would't just run from left to right. First a==b is evaluated then b==c and then && operator. Can you please explain more?
That's not how the expression is processed.
In Java, all expressions are evaluated from left to right. Operator precedence only comes into play when considering the evaluation of the arguments of &&.
So i < 5 is computed before ++i < 5 is even considered.
In this case ++i < 5 will not be evaluated, since i < 5 is false. So i stays at 5.
The key is: ++ has the highest precedence inside a expression, but the sentence boolean b = i<5 && ++i<5 has two expressions evaluated from left to right.
Think of b = i<5 && ++i<5 like:
if( i<5 ){
if ( ++i<5 ){
return true;
}
}
Considering your edited answer, the second code snippet also evaluates from left to right.
In both cases there is an expression of the form A && B with A as the left argument and B as the right argument of &&.
Here is where "left-to-right" applies. First, the left expression A is evaluated. In your first code snippet, that is i<5 and since this expression evaluates to false, the second argument to that isn't even considered, since the whole expression will evaluate to false (short-circuiting).
In your second snippet you have as left argument a==b. Since that evaluates to true, only now the second argument is considered, which also evaluates to true. That leaves you with true && true which can then be processed further.
Your misunderstanding is in how the '&&' works. When you use them java uses short circuit or lazy evaluation.
boolean equal = 1==1 && 1==2 java evaluates the 1==1 sees it as true, checks the ampersands and has to evaluate the 1==2 which is false and therefore equal is false.
boolean equal = 1==2 && 1==1 java evaluates the 1==2 sees it as false, then checks the ampersands and can see that whether the next expression is true or false the outcome is the same, that equal is false. Therefor it never evaluates the second equation.
More plainly the second example is saying boolean equal = false & true. This can only be true if both are true. Thus knowing the first is false is all we need to know the outcome. By ignoring the sencond expression at this point we can save needless calculations.

When does an if statement finish checking its conditions? [duplicate]

This question already has answers here:
Java logical operator short-circuiting
(10 answers)
Closed 6 years ago.
When an if statement contains two (or more) conditions, and the first one fails, does the if statement check the second condition or continue on in the code?
Here are two examples:
int x = 1, y = 2;
if(x == 0 && y == 2)
System.out.println("Nothing");
if(x == 1 || y == 0)
System.out.println("Something");
In the first if statement, the conditions should return false, but is y == 2 even tested? And in the second example, the conditions should return true, but is y == 0 tested at all? Or in both cases, after the first condition, the code skips the second condition and continues on in the code?
Thanks in advance.
&& and || are short-circuit operators, which means the right hand side comparison won't be evaluated if it isn't necessary.
So, we have the following:
When using &&, if the left hand side comparison is false, the right hand side comparison is not evaluated.
When using ||, if the left hand side comparison is true, the right hand side comparison is not evaluated.
However, when using & and | as logical operators, both sides will always be evaluated.
Just like #Cassio stated, the second operand will not be evaluated.
Short circuit evaluation is really handy when you need to check for an object existence and validate it's properties, for example.
if (X !=null && X.length !=null) ...
In && operator both comparison must return true to pass the if condition so if the first one is false the result will be false whatever the second result is.
In || operator if any of the comparison is true, the if result will be true whatever the second result is.
So,
In the AND operator it will test the second comparison if the first one is true and it need to test the second comparison to determine the condition result.
In the OR operator it will test the second comparison if the first one is false and it need to test the second because it could change the condition result if it's true.

short circuit operators give me different result [duplicate]

This question already has answers here:
What is wrong with the short circuit logic in this Java code?
(9 answers)
Closed 8 years ago.
While using the short-circuit operators && and ||, I'm getting unexpected results.
if(false && false || true) {
System.out.println("true");
} else {
System.out.println("false");
}
It gives me true but according to short-circuit rule if the first operand is false then it is not necessary to evaluate the second operand. Can anyone explain it where I'm missing something.
(false && false) || true
is evaluated first. Short-circuit gives false and thus the || cannot be short-circuited, and is thus fully evaluated,
My interpretation is that, because the && operator has higher precedence than || (according to this table), the statement gets interpreted as (false && false) || true.
This then evaluates to false || true, which is of course true. I could be wrong, but that's what seems to be going on.
You are not reading the short circuit rules correctly.
The rule you stated applies to AND (&&) operation only. Clearly the result of the first operation is false. Now you need to perform the second operation OR (||). The rule for OR is exact opposite, if first operand is TRUE the second doesn't need to be evaluated. In your case the first operand is false, so second operand of || needs to be evaluated. The result of second operand is true. So the result of the whole expression is true.
I think from JDK 7 the short-circuit rule has been redefined because when I tried to run in JDK 6 it gives me the correct answer but when I run it in JDK 7 it gives me unexpected result.

What is the difference between & and && in if statement in java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference in & and &&
if (true && true) {
System.out.println("test if");
}
if (true & true) {
System.out.println("test if");
}
both are give same output.why ?
&& short-circuits, wheras & doesn't. Example:
if (methodA() && methodB()) {
...
}
In that case, if methodA already returns false, methodB is not called. Formally, if you have an expression a && b, b is only evaluated if a evaluated to true.
Apart from the obvious performance benefit, this is particularly useful for null checks:
if (x != null && x.getSomeValue()) {
...
}
If you used a s single & here, x.getSomeValue() would be evaluated even if x were null, resulting in an exception.
& is a bit operation
&& logically links two booleans
Please see:
http://www.jguru.com/faq/view.jsp?EID=16530
It depends on the type of the arguments...
For integer arguments, the single ampersand ("&")is the "bit-wise AND"
operator. The double ampersand ("&&") is not defined for anything but
two boolean arguments.
For boolean arguments, the single ampersand constitutes the
(unconditional) "logical AND" operator while the double ampersand
("&&") is the "conditional logical AND" operator. That is to say that
the single ampersand always evaluates both arguments whereas the
double ampersand will only evaluate the second argument if the first
argument is true.
For all other argument types and combinations, a compile-time error
should occur.
In the first case, you don't test the second part of the if : the && operator executes from left to right and stops at the first false value.
This may be useful in this case :
if (a!=null && a.doSomething()==23) {
because it prevents a nullPointerException.
When you test boolean conditions, always use &&.
In & statetment it will check both left side and right side statements.in && will check only one side of statement(if one side is true it will not check other side)
&& is the logical AND
so you want to make sure BOTH statements become true.
& is the bitwise AND operator
Have a look here:
http://www.javaforstudents.co.uk/TrueFalse
&& is logical and.
true && true is true and everything else is false.
& is bitwise and.
(10 & 8) = 8

What does this myCar evaluate to? Is it the return value of somePart()?

What does this myCar evaluate to? Is it the return value of somePart()?
boolean myCar = true || somePart();
The || operator is called a "short-circuit" operator, because if it finds that evaluating the left operand results in true, it will not bother evaluating the right operand. In your case, true is true, so somePart() will not be called.
I would assume it would always return true. Infact somePart() would never be evaluated.
it's evaluated to true, somePart() is never called.
It will always return true, as a result of Short-circuit Evaluation.
Read it out loud.
"myCar equals TRUE -or- somePart()"
We can short circuit the function evaluation since the first condition always returns true.
This will always return true even if somePart() returns false. Because somePart() will not even be executed. JVM optimizes logical expressions and does not run the rest of expression if the result is known anyway.
It will be true. Always. Because of the behavior of the logical or operator is this:
Input 1 Input 2 Output
------- ------- ------
0 0 0
0 1 1
1 0 1
1 1 1
Since it is a || operator between true and somePart(), it would always return true.
It checks if either of the condition is true, if it finds such a condition which is true, then it is set to true. This is the an indirect reason why the call to somePart() is never evaluated.

Categories

Resources