Java control flow matches C-family languages: if/else, switch, for, while, and enhanced for-each over arrays and collections.
if and switch
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
}
switch (day) {
case "MON" -> System.out.println("Start week");
case "FRI" -> System.out.println("Almost weekend");
default -> System.out.println("Midweek");
}
Modern switch expressions (Java 14+) can return values with arrow syntax.
Loops
for (int i = 0; i < 3; i++) { }
for (String item : items) { }
Important interview questions and answers
- Q: switch on String since when?
A: Java 7+ supports String in switch; use expressions in modern code. - Q: break vs continue?
A:breakexits the loop;continueskips to the next iteration.
Self-check
- Write the enhanced-for loop syntax for a
String[]. - When is a
switchclearer than chainedif-else?
Pitfall: Classic switch cases fall through without break—prefer arrow syntax (case X ->) in modern Java.