Java Logical Operators
In this page:
Logical AND (&&)
&& only evaluates to true when both surrounding boolean expressions are true; a single false expression on either side makes the whole combined expression false, regardless of the other side.
Example: Logical AND (&&)
public class Main {
public static void main(String[] args) {
boolean loggedIn = true;
boolean verified = false;
System.out.println(loggedIn && verified); // false - one side is false
}
}
Login to try C/C++/Java/PHP code in the editor
Logical OR (||)
|| evaluates to true if at least one side is true, and only becomes false when both sides are false -- useful for conditions like 'if the user is an admin OR has explicit access'.
Example: Logical OR (||)
public class Main {
public static void main(String[] args) {
boolean isAdmin = false;
boolean hasAccess = true;
System.out.println(isAdmin || hasAccess); // true - at least one side is true
}
}
Login to try C/C++/Java/PHP code in the editor
Logical NOT (!)
! simply flips a boolean's value: applying it to a true expression gives false, and to a false expression gives true, which is handy for readably expressing not conditions like !isEmpty.
Example: Logical NOT (!)
public class Main {
public static void main(String[] args) {
boolean isEmpty = false;
System.out.println(!isEmpty); // true - flips the value
}
}
Login to try C/C++/Java/PHP code in the editor
Short-circuit Evaluation
Because && stops evaluating as soon as it hits a false operand (and || stops as soon as it hits a true one), you can safely write list != null && list.size() > 0 -- the size() call never runs if list is already null.
Example: Short-circuit Evaluation
public class Main {
public static void main(String[] args) {
String list = null;
System.out.println(list != null && list.length() > 0); // list.length() never runs
}
}
Login to try C/C++/Java/PHP code in the editor
Combining Logical Operators
Wrapping sub-expressions in parentheses, like (a && b) || c, makes the intended evaluation order explicit rather than relying on the reader to remember Java's default operator precedence rules.
Example: Combining Logical Operators
public class Main {
public static void main(String[] args) {
boolean a = true, b = false, c = true;
System.out.println((a && b) || c); // parentheses make evaluation order explicit
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: