Java Logical Operators
Logical operators let you combine or flip boolean values so you can express more complex conditions than a single comparison allows. With them you can say things like "the user is logged in AND has permission" or "the field is empty OR too long".
The three logical operators
Java provides three logical operators. Two of them combine two booleans, and one flips a single boolean to its opposite.
AND, OR, and NOT in action
The example below combines comparisons with logical operators to make richer decisions. Read each condition aloud in plain English to check your understanding.
Combining conditions
public class Main {
public static void main(String[] args) {
int age = 25;
boolean hasTicket = true;
boolean canEnter = age >= 18 && hasTicket; // both must hold
boolean needsHelp = age < 12 || age > 65; // either qualifies
boolean noTicket = !hasTicket; // flips true to false
System.out.println(canEnter); // true
System.out.println(needsHelp); // false
System.out.println(noTicket); // false
}
}Checking a range
A very common use of && is testing whether a value falls between two bounds. Java has no single between operator, so you combine two comparisons instead.
Is the number in range?
public class Main {
public static void main(String[] args) {
int temperature = 22;
if (temperature >= 18 && temperature <= 24) {
System.out.println("Comfortable");
} else {
System.out.println("Adjust the thermostat");
}
// prints: Comfortable
}
}Note: Java uses short-circuit evaluation. With &&, if the left side is false Java skips the right side entirely because the whole result must be false. With ||, if the left side is true it skips the right side. This can save work and helps you guard against errors.
- AND (&&) is strict: every condition must be true.
- OR (||) is lenient: only one condition needs to be true.
- NOT (!) reverses whatever boolean it is placed in front of.
- Wrap combined conditions in parentheses to make the grouping crystal clear.
Note: The single characters & and | also exist in Java but they are bitwise operators and do not short-circuit. For everyday true/false logic, stick with the doubled && and ||.