Challenge - 5 Problems
Break Statement Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of break in nested loops
What is the output of this Java code snippet?
Java
public class Test { public static void main(String[] args) { int count = 0; outer: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i * j > 3) { break outer; } count++; } } System.out.println(count); } }
Attempts:
2 left
💡 Hint
Look at how the labeled break exits the outer loop immediately.
✗ Incorrect
The inner loop increments count while i*j <= 3. When i=2 and j=2, i*j=4 > 3, so break outer exits both loops. The count increments 4 times before breaking.
🧠 Conceptual
intermediate2:00remaining
Effect of break in switch-case
What will be printed when the following Java code runs?
Java
public class Test { public static void main(String[] args) { int x = 2; switch (x) { case 1: System.out.println("One"); case 2: System.out.println("Two"); case 3: System.out.println("Three"); break; default: System.out.println("Default"); } } }
Attempts:
2 left
💡 Hint
Remember that break stops execution inside switch cases.
✗ Incorrect
Since case 2 matches, it prints "Two" then falls through to case 3 and prints "Three" before break stops further execution.
🔧 Debug
advanced2:00remaining
Why does this break not stop the loop?
Consider this Java code. Why does the loop terminate immediately without printing any numbers instead of stopping at 3?
Java
public class Test { public static void main(String[] args) { for (int i = 0; i < 5; i++) { if (i == 3); break; System.out.println(i); } } }
Attempts:
2 left
💡 Hint
Check the semicolon after the if condition carefully.
✗ Incorrect
The semicolon after if(i == 3) ends the if statement. The break is outside the if and executes unconditionally on first iteration.
📝 Syntax
advanced2:00remaining
Identify the syntax error with break usage
Which option shows the code that will cause a compile-time error due to incorrect break usage?
Java
public class Test { public static void main(String[] args) { // Code snippet here } }
Attempts:
2 left
💡 Hint
break must be inside a loop or switch block.
✗ Incorrect
Option A uses break outside any loop or switch, causing compile-time error.
🚀 Application
expert2:00remaining
Count iterations before break in nested loop
What is the value of variable total after running this Java code?
Java
public class Test { public static void main(String[] args) { int total = 0; outer: for (int i = 1; i <= 4; i++) { for (int j = 1; j <= 4; j++) { if (i + j > 5) { break outer; } total++; } } System.out.println(total); } }
Attempts:
2 left
💡 Hint
Count how many times total increments before i+j > 5 triggers break.
✗ Incorrect
The loops increment total while i+j <= 5. The break outer stops both loops when i+j > 5. Counting increments gives 7.