Archive for April, 2008

Know your Logic. About: &&, &, || and | operators.

Tuesday, April 8th, 2008

Know Your Logic

https://duke.dev.java.net/images/misc/DukeTango.pngMany 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 :)