Skip to main content

2.4 Operators & Modern Control Flow

← Back to Chapter 2: Java Overview & Memory Model

Java provides standard arithmetic, bitwise, and logical control flow constructs, enriched significantly in recent LTS releases with expressive switch expressions and pattern matching.


1. Short-Circuit Logical Operators​

  • && (Logical AND): If the left operand evaluates to false, the right operand is never evaluated.
  • || (Logical OR): If the left operand evaluates to true, the right operand is never evaluated.
// Safe null-check using short-circuit evaluation
if (user != null && user.isActive()) {
processOrder(user);
}

2. Modern Switch Expressions (Java 14+)​

The legacy switch statement was error-prone due to accidental fall-through (break omission). Modern Java introduces Switch Expressions with arrow syntax (->) and return values:

public enum OrderStatus { NEW, PROCESSING, SHIPPED, DELIVERED, CANCELLED }

public static String describeStatus(OrderStatus status) {
return switch (status) {
case NEW, PROCESSING -> "In preparation";
case SHIPPED -> "Out for transit";
case DELIVERED -> "Successfully completed";
case CANCELLED -> {
logCancellationAlert();
yield "Refund pending"; // Use yield for multi-statement blocks
}
};
}

3. Pattern Matching for Switch (Java 21 LTS)​

Java 21 stabilizes pattern matching for switch, allowing inspection of types and null-safety directly:

public static String formatObject(Object obj) {
return switch (obj) {
case null -> "Null Reference";
case Integer i -> String.format("Integer value: %d", i);
case Long l -> String.format("Long value: %d (64-bit)", l);
case String s when s.isBlank() -> "Empty string";
case String s -> "String of length " + s.length();
default -> obj.toString();
};
}