Control Flow
TL;DR
Control flow statements break up the flow of execution by employing decision-making, looping, and branching, enabling your program to conditionally execute particular blocks of code.
- Decision Making:
if,else,switch - Looping:
for,while,do-while - Branching:
break,continue,return
Concept
By default, statements in a script are executed sequentially from top to bottom. Control flow dictates how this top-to-bottom sequence is altered.
Switch Statement (Java 14+)
The traditional switch has been upgraded in modern Java (Java 14+) with switch expressions, avoiding the need for break statements and allowing it to return a value directly.
Enhanced For Loop
The “for-each” loop is used exclusively to loop through elements in an array or a Collection (like a List).
Examples
public class ControlFlow {
public static void main(String[] args) {
// 1. Enhanced For-Loop
String[] fruits = {"Apple", "Banana", "Cherry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
// 2. Modern Switch Expression (Java 14+)
String day = "MONDAY";
boolean isWeekend = switch (day) {
case "SATURDAY", "SUNDAY" -> true;
case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> false;
default -> throw new IllegalArgumentException("Invalid day: " + day);
};
}
}
Interview Questions
Q: What is the difference between while and do-while?
A: A while loop checks the condition before executing the block. If the condition is false initially, the block is never executed. A do-while loop executes the block first, and then checks the condition. Therefore, a do-while loop will always execute at least once.
Q: Can we use strings in a switch case?
A: Yes. Prior to Java 7, switch only worked with byte, short, char, and int (and their wrappers). Since Java 7, you can use String objects in a switch statement. Since Java 14, you can also use Switch Expressions.