The material below assumes familiarity with Short circuit evaluation of boolean expressions.
The Java logical operators !
, &&
, ||
(not, and, or) are shown below from highest to lowest precedence.
!
&&
||
The relative precedence of &&
and ||
is commonly misunderstood. This is particularly true when combined with short circuit evaluation of boolean expressions.
Operator precedence dictates which part(s) of a boolean expression are grouped together. The left operand of an &&
or an ||
is evaluated first. Short circuit evaluation determines whether the right operand is evaluated.
Example 1
boolean a = true, b = true, c = false;
System.out.println(a || b && c);
The example prints: true
a || b && c
is equivalent to:
a || (b && c)
The left side of the ||
is evaluated first. a
is true
. The expression becomes:
true || (b && c)
Short circuit evaluation means that the entire expression evaluates to true
. The expression b && c
is not evaluated.
Example 2
boolean a = true, b = true, c = false;
System.out.println((a || b) && c);
The example prints: false
a || b
is evaluated first. a
and b
are both true
. true || true
evaluates to true
. The expression becomes:
true && c
c
is false
. true && false
evaluates to false
.
Example 3
boolean a = true, b = true;
System.out.println( !b || a );
The example prints: true
!b || a
is equivalent to:
(!b) || a
!b
is evaluated first. b
is true
so !b
is false
. The expression becomes:
false || a
a
is true
. false || true
evaluates to true
.
Example 4
boolean a = true, b = true;
System.out.println( !(b || a) );
The example prints: false
b || a
is evaluated first. Both a
and b
are true
. true || true
evaluates to true
. The expression becomes:
!(true)
!true
evaluates to false
.
Another example with short circuit
int x = 5, y = 0, z = 3;
System.out.println(y == 0 || x / y > 1 && z <= 3); // prints true
y == 0 || x / y > 1 && z <= 3
is equivalent to:
y == 0 || (x / y > 1 && z <= 3)
y == 0
is evaluated first as true
. Since the left operand of the ||
is true
, the entire expression evaluates to true
.
The expression x / y > 1 && z <= 3
is never evaluated. This is important since y
is 0
. 5 / 0
would result in an ArithmeticException
if it was evaluated.
This example illustrates how operator precedence and short circuit evaluation work together. Operator precedence dictates which parts of the expression are grouped together. Short circuit evaluation still applies to the resulting expression.
Help & comments
Get help from AP CS Tutor Brandon Horn