Java Logical Operators - And Or
The ShortCircuit program
The ShortCircuit
program illustrates the short-circuit behavior of the &&
and ||
operators.
It displays the following output:
false true false
false false
true false true
true true
You should note that only two values are displayed on the second and fourth lines. That's because in these cases, the &&
and ||
operators skipped the evaluation of the second operands.
These operands were evaluated by the &
and |
operators.
ShortCircuit
public class ShortCircuit {
public static boolean display(boolean b) {
System.out.print(b + " ");
return b;
}
public static void main(String[] args) {
boolean t = true;
boolean f = false;
System.out.println(display(f) & display(t));
System.out.println(display(f) && display(t));
System.out.println(display(t) | display(f));
System.out.println(display(t) || display(f));
}
}