← Back to Core Java Course | Chapter 3: Operators | Lesson 4 of 9

Java Logical Operators

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 (&&)

java
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
	}
}

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 (||)

java
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
	}
}

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 (!)

java
public class Main {
	public static void main(String[] args) {
		boolean isEmpty = false;
		System.out.println(!isEmpty); // true - flips the value
	}
}

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

java
public class Main {
	public static void main(String[] args) {
		String list = null;
		System.out.println(list != null && list.length() > 0); // list.length() never runs
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.