1Z0-808 · Question #59
Given the code fragment: 4. public static void main(String[] args) { 5. boolean opt = true; 6. switch (opt) { 7. case true: 8. System.out.print("True"); 9. break; 10. default: 11…
The correct answer is A. Replace line 5 With String result = "true". Option A works because Java's switch statement does not support boolean as a switch expression - the code as written won't compile at all. Changing line 5 to String result = "true" (with the switch expression and case label updated to match) allows the switch to work, since…
Question
- public static void main(String[] args) {
- boolean opt = true;
- switch (opt) {
- case true:
- System.out.print("True");
- break;
- default:
- System.out.print("****");
- }
- }
- Which modification enables the code to print TrueDone?
Options
- AReplace line 5 With String result = "true";
- BReplace line 7 with case "true":
- CAt line 9, remove the break statement.
- DRemove the default section.
How the community answered
(26 responses)- A77% (20)
- B15% (4)
- C4% (1)
- D4% (1)
Explanation
Option A works because Java's switch statement does not support boolean as a switch expression - the code as written won't compile at all. Changing line 5 to String result = "true" (with the switch expression and case label updated to match) allows the switch to work, since Java has supported String in switch statements since Java 7; the "True" branch executes, then code after the switch block prints "Done", producing "TrueDone".
Option B alone fails because even with case "true":, the switch expression on line 6 still uses a boolean, which remains invalid. Option C is wrong because removing the break causes fall-through into the default block, printing "True****" instead of "TrueDone". Option D is a distractor - removing default doesn't fix the fundamental type mismatch that prevents compilation.
Memory tip: Think "switch won't flick a boolean" - Java switch only accepts int-compatible types (byte, short, char, int), enums, and String. Any time you see a boolean in a switch expression on an exam, the code is invalid and the fix must change the type.
Topics
Community Discussion
No community discussion yet for this question.