Skip to main content
Advertisement

3.5 Logical Operators

Used to form more complex conditions by combining the results of comparison operations or logical values. They take boolean types (true/false) as operands.

1. Logical Operators (&&, ||)

  • && (AND): The result is true only when both operands are true. If even one of them is false, it returns false.
  • || (OR): The result is true if at least one of the two operands is true. It returns false only when both are false.
int x = 5;

// x is greater than 0 AND less than 10.
boolean result1 = (x > 0) && (x < 10); // true

// x is less than 0 OR greater than 10.
boolean result2 = (x < 0) || (x > 10); // false

Short Circuit Evaluation

In Java, logical operations evaluate expressions from left to right.

  • For the || operation: If the left operand is true, the overall result is already confirmed as true, so the right expression is not even evaluated (executed).
  • For the && operation: If the left operand is false, it is false regardless of whether the right condition is true or false, so the right expression is ignored.

Therefore, for faster execution, it is advantageous to place conditions that are highly likely to determine the outcome on the left side of the logical operation.

2. Ternary Operator (? :)

The ternary operator is the only operator that requires three operands and is mainly used to represent an if statement concisely. The result returned differs depending on whether the conditional expression is true or false.

(Conditional Expression) ?(Value to return if true) :(Value to return if false)

int x = 10, y = 5;

// If x is greater than y, return the value of x, otherwise return the value of y
int max = (x > y) ? x : y;

System.out.println(max); // Output will be 10

Using the ternary operator can make the code concise, but overusing it with nesting can actually reduce readability. It is better to use if - else blocks in complex areas.

Advertisement