Wednesday, 18 July 2012

What is difference between | and || in java.


The operators || and && are called conditional operators, while | and & are called bitwise operators. They serve different purposes.
Conditional operators works only with expressions that statically evaluate to boolean on both left- and right-hand sides.
Bitwise operators works with any numeric operands.
If you want to perform a logical comparison, you should use conditional operators, since you will add some kind of type safety to your code.
a | b: evaluate b in any case

a || b: evaluate b only if a evaluates to false


| is the binary or operator
|| is the logic or operator



Below are some conclusion here : 
  • the operand of every expression is evaluated before the operation is performed except for the short-circuit operators (&&, ¦¦) and ternary operator
  • behaviour can produce unexpected results if you're not careful. For example, the following code illustrates what can occur if you try to set the value of a variable in an if condition and you always expect the new value to be available:
int i = 10;
int j = 12;

if( (i<j) ¦  (i=3) > 5 )   // value of i after oper: 3
if( (i<j) ¦¦ (i=3) > 5 )   // value of i after oper: 10

if( (i>j) &  (i=3) > 5 )   // value of i after oper: 3
if( (i>j) && (i=3) > 5 )   // value of i after oper: 10
  • with & and ¦ both operands are always evaluated
  • with && and ¦¦ the second operand is only evaluated when it is necessary
  • with ¦¦ (i<j) evaluates to true; there is no need to check the other operand as ¦¦ returns true if either of the operands are true
  • with && (i>j) evaluates to false; there is no need to check the other operand as && returns true only if both operands are true. In this case one is false so there is no need to check the other operand

No comments:

Post a Comment