2

I am getting the out same output: a | b = false a || b = false a | b = true a || b = true a | b = true a || b = true a | b = true a || b = true

What is the difference between these two operators ? 

boolean a = false;  
boolean b = false;  

System.out.println("a | b = " + (a|b) );
System.out.println("a || b = " + (a||b) );

a = false;  
b = true;   
System.out.println("a | b = " + (a|b) );
System.out.println("a || b = " + (a||b) );

a = true;   
b = false;  
System.out.println("a | b = " + (a|b) );
System.out.println("a || b = " + (a||b) );

a = true;   
b = true;   
System.out.println("a | b = " + (a|b) );
System.out.println("a || b = " + (a||b) );
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
Dhanuka Perera
  • 1,395
  • 3
  • 19
  • 29

1 Answers1

4

The difference is that the short circuit operator doesn't evaluate the second operand if the first operand is true, which the logical OR without short circuit always evaluates both operands.

You wouldn't see any difference in your simple test, since both should give the same output assuming no exception is thrown, but if you try something like this :

String s = null;
System.out.println("a || b = " + s==null || s.length() == 0 );
System.out.println("a | b = " + s==null | s.length() == 0 );

The first operator will give you true, while the second operator will give you NullPointerException, since only the | operator will attempt to evaluate s.length() == 0.

Eran
  • 387,369
  • 54
  • 702
  • 768