1Z0-809 · Question #82
Given: class Test { int sum = 0; public void doCheck(int number) { if (number % 2 == 0) { break; } else { for (int i = 0; i < number; i++) { sum += i; } } } public static void main(String[] args) {…
This code fails to compile, making C the correct answer. The break statement on line 4 of doCheck appears inside a plain if block - Java only permits break inside a loop (for, while, do-while) or a switch statement. Using it anywhere else is a compile-time error, so the program…
Question
Options
- ARed 0 Orange 0 Green 3
- BRed 0 Orange 0 Green 6
- CRed 0
Explanation
This code fails to compile, making C the correct answer. The break statement on line 4 of doCheck appears inside a plain if block - Java only permits break inside a loop (for, while, do-while) or a switch statement. Using it anywhere else is a compile-time error, so the program never runs.
A and B are wrong because they both assume the program executes successfully and prints output - that's impossible when compilation fails first. If you try to reason through the logic anyway: A assumes sum stays 0 after doCheck(2) (which is correct since 2 is even) and reaches 3 after doCheck(3) (0+1+2=3, also correct), but the code never gets that far. B is wrong on the math too - 0+1+2 = 3, not 6.
Memory tip: In Java, break needs something to break out of - a loop or a switch. A bare if/else gives it nowhere to go, so the compiler rejects it. Think: "break breaks out of brackets that repeat or branch on values, not plain conditionals."
Community Discussion
No community discussion yet for this question.