4.1 Decision Making: if, if-else, switch
Control flow statements determine the execution path of a program based on runtime conditions. Java provides standard conditional branching via if, else if, and else, evaluating boolean expressions from top to bottom.
Evolution of the Switch Statement in Java
Java's switch extends the traditional C-style switch in two major architectural ways:
- String Support: Since Java 7,
Stringobjects can be used as switch selectors and case labels (evaluated using.hashCode()and.equals()under the hood). C only allows primitive integral types. - Enhanced Arrow Switch Expression (Java 14+): The traditional colon syntax suffered from accidental fall-through bugs when a developer forgot a
breakstatement. Java introduced arrow syntax (case ->), which eliminates fall-through entirely and allows the switch to act as an expression that evaluates directly to a value:
int marks = 85;
String grade = switch (marks / 10) {
case 10, 9 -> "A";
case 8 -> "B";
case 7 -> "C";
default -> "D";
};
System.out.println("Grade: " + grade);
💡 Placement & Interview Deep-Dive
- Which data types are NOT permitted in a Java switch statement?
float,double, andbooleancannot be used in a switch statement! Allowed types arebyte,short,char,int, their corresponding wrapper classes (Byte,Short,Character,Integer),String, andenumconstants. - What is the
yieldkeyword in Java switch expressions? In multi-line code blocks within a Java 14+ switch expression,yield value;is used to explicitly return a value from that case branch, replacing the traditionalbreakstatement.
4.2 Loops: for, while, do-while, for-each
Loops allow repeated execution of a code block until a boolean termination condition evaluates to false. Java provides four loop structures:
- Traditional
forloop: Ideal when the number of iterations is known beforehand. Comprises initialization, test condition, and increment/update. whileloop: Entry-controlled loop. Evaluates condition before each iteration; executes 0 or more times.do-whileloop: Exit-controlled loop. Evaluates condition after the loop body executes, guaranteeing at least one execution regardless of condition.- Enhanced
for-eachloop: Iterates cleanly through arrays andIterablecollections without explicit loop counter indices:int[] scores = {90, 85, 78, 92}; for (int s : scores) { System.out.println("Score: " + s); }
💡 Placement & Interview Deep-Dive
- Can you modify an ArrayList while iterating over it in a for-each loop? NO! Calling
list.add()orlist.remove()inside an enhanced for-each loop throws aConcurrentModificationException. The enhanced for loop uses an internalIteratorthat checksmodCount. To safely remove items during iteration, you must use an explicitIteratorand calliterator.remove(). - Infinite loop idioms in Java: Both
for(;;)andwhile(true)produce identical bytecode instructions (an unconditional jumpgoto).
4.3 break, continue, and Labeled Statements
Loop execution can be dynamically controlled using break and continue statements:
break: Immediately exits the nearest enclosing loop or switch block, resuming execution at the statement following the loop.continue: Immediately skips the remainder of the current loop iteration and advances directly to the next iteration's test/update step.
The Structured Solution to Goto: Labeled Statements
Java has no goto statement. However, in deeply nested loops (e.g. searching a 2D matrix), breaking out of only the innermost loop requires tedious boolean flag management. Java provides labeled break and continue:
outer: // label definition
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
System.out.println("Breaking outer loop from inside!");
break outer; // Breaks completely out of the outer loop
}
System.out.println("i=" + i + ", j=" + j);
}
}
A structured, readable alternative to goto — they let you control exactly which outer loop a break or continue applies to, instead of always affecting only the innermost one.