Why are there 2 boolean operators in Java?

As they say in Java thinking, if you have 2 boolean objects, x and y , you can use both x= x&&y and x=x&y , so why should it be of both types?

+4
source share
4 answers

Both operators act differently:

  • & will always evaluate both operands
  • && - short circuit - if the first operand evaluates to false , then the overall result will always be false, and the second operand will not evaluate

See the Java Language Specification for more details:

+12
source

Look at the output of this code:

  int x = 0; boolean b = false & (++x == 1); // b is false System.out.println(x); // prints 1 x = 0; b = false && (++x == 1); // b is false System.out.println(x); // prints 0 

This is different in that & will always evaluate both operands, while && will not look at the second operand if the first is false , because the whole expression will always be false regardless of what the second operand is.

+3
source
  • & will evaluate both operands
  • && skip evaluating the second operand if the first operand is false
+2
source

& is the hit "and" operator, && is the boolean 'and'

& will always evaluate both the left and right sides, && will evaluate only the left if this is enough to evaluate the expression (for example, false && true: only LHS is evaluated, because if LHS is false, the whole expression must be false)

+1
source

All Articles