Logical operators in Java
Logical operators in Java are used to combine multiple boolean expressions or conditions, and they are essential for writing decision-making logic like if statements and loops.
Logical AND (&&)
Returns true only if both conditions on either side are true. It uses short-circuit evaluation, meaning the second condition isn't checked if the first is already false.
int age = 25;
boolean hasID = true;
if (age >= 18 && hasID) {
System.out.println("Entry allowed");
}
Logical OR (||)
Returns true if at least one of the two conditions is true. It also short-circuits — if the first condition is true, the second is never evaluated.
boolean isWeekend = true;
boolean isHoliday = false;
if (isWeekend || isHoliday) {
System.out.println("No work today");
}
Logical NOT (!)
Reverses the value of a boolean expression — true becomes false and vice versa.
boolean isLoggedIn = false;
if (!isLoggedIn) {
System.out.println("Please log in");
}
Truth Table
true && true→truetrue && false→falsefalse || true→truefalse || false→false!true→false
Short-Circuit Evaluation
Java also provides non-short-circuit versions, & and |, which always evaluate both sides. These are rarely used for boolean logic but matter to know, since && and || skip unnecessary evaluations for better performance and to avoid errors like calling a method on a null object.
obj != null && obj.isValid() safely.Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.