STUDYECRAT Java : Control Flow
60s
Java : Control Flow
Prove your skills in this interactive quiz
Live Code
Run snippets directly
Timed
60s per question
Scored
Earn 3D badges
★ Java Control Flow: Key Interview Points
1. Switch Fall-Through Behavior
int day = 2;
switch (day) {
case 1: System.out.print("Mon");
case 2: System.out.print("Tue"); // No break
case 3: System.out.print("Wed"); break;
}
// Output: TueWed (Fall-through executes all until break)
switch (day) {
case 1: System.out.print("Mon");
case 2: System.out.print("Tue"); // No break
case 3: System.out.print("Wed"); break;
}
// Output: TueWed (Fall-through executes all until break)
- Tip: Always use
break
unless intentional fall-through is needed. - Real Use: Calendar apps where multiple cases share logic (e.g., weekdays).
2. Ternary Operator vs If-Else
int x = 10;
String result = (x > 5) ? "Pass" : "Fail";
System.out.println(result);
// Output: Pass (Ternary is concise but less readable for complex logic)
String result = (x > 5) ? "Pass" : "Fail";
System.out.println(result);
// Output: Pass (Ternary is concise but less readable for complex logic)
- Tip: Avoid nested ternaries—they reduce code clarity.
- Real Use: Configuring default values in Spring Boot properties.
3. Breaking Nested Loops with Labels
outerLoop: // Label
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) break outerLoop;
System.out.print(i + "" + j + " ");
}
}
// Output: 00 01 02 10 (Breaks both loops at i=1, j=1)
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) break outerLoop;
System.out.print(i + "" + j + " ");
}
}
// Output: 00 01 02 10 (Breaks both loops at i=1, j=1)
- Tip: Use labels sparingly—they can make code harder to debug.
- Real Use: Matrix traversal algorithms (e.g., Sudoku solvers).
4. Do-While Guaranteed Execution
int count = 0;
do {
System.out.print(count + " ");
count++;
} while (count < 0);
// Output: 0 (Runs once even if condition is false)
do {
System.out.print(count + " ");
count++;
} while (count < 0);
// Output: 0 (Runs once even if condition is false)
- Tip: Prefer
do-while
for input validation loops. - Real Use: ATM menus where the user must see options first.
5. For-Loop Variable Scope
for (int i = 0; i < 2; i++) {
System.out.print(i + " ");
}
System.out.print(i); // Compile error
// 'i' is scoped ONLY within the loop
System.out.print(i + " ");
}
System.out.print(i); // Compile error
// 'i' is scoped ONLY within the loop
- Tip: Declare loop counters outside if needed later.
- Real Use: Memory optimization in large-scale iterations.
💡 Pro Interview Tip
When asked about control flow, always mention short-circuit evaluation (&&
, ||
). Example: if (x != null && x.isEmpty())
avoids NullPointerException.