Know your Logic. About: &&, &, || and | operators.
Know Your Logic
Many are not aware of the optimized logic statements. This could lead to the logic errors. In Java there are two AND and two OR statements. One is optimized and one is not. The optimized operator will not evaluate a second (right) statement if the final outcome is clear from evaluation of the first (left) statement.
For example, A || B, if A is TRUE the result of the statement is TRUE regardless of what B evaluates to. Therefore B will not be evaluated. That is an optimized OR statement, if you require that both sides of the operator evaluated, use unoptimized operator |. That would be, A | B, so even if A is true, B will be evaluated regardless.
The AND operator works in a similar fashion. For example, A && B, if A evaluates to FALSE the result of the statement will be FALSE regardless of what B evaluates to. Therefore B will not be evaluated. Again, if you require both sides of the expression evaluated, use unoptimized & operator.
That would be, A & B, so event if A evaluates to false, B will be evaluated regardless.
See this example:
class test {
public static boolean checkSomething( String from ){
System.out.println(”checkSomething() from-> ” + from );
return true;
}
public static void main( String [] arg ){
if( true || checkSomething(” || “) )
System.out.println(” || test”);
if( true | checkSomething( ” | “) )
System.out.println(” | test”);
if( false && checkSomething( ” && “) )
System.out.println(” && test” );
if( false & checkSomething( ” & “) )
System.out.println(” & test” );
}
}
Output:
|| test
checkSomething() from-> |
| test
checkSomething() from-> &
You can see, that checkSomething(String) is evaluated only with unoptimized operators.
Know your logic! Code bug free!
I know you want to, give us a jiggle
April 8th, 2008 at 3:17 pm
I didn’t even realize that there was an unoptimized version. Thanks for the info.
It might be interesting to write a quick performance program to see if there is any impact for something simple like mathematical evaluations.