nerdexam
Oracle

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…

Using Operators and Decision Constructs

Question

Given the code fragment:
  1. public static void main(String[] args) {
  2. boolean opt = true;
  3. switch (opt) {
  4. case true:
  5. System.out.print("True");
  6. break;
  7. default:
  8. System.out.print("****");
  9. }
  10. }
  11. 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)
  • A
    77% (20)
  • B
    15% (4)
  • C
    4% (1)
  • D
    4% (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

#switch statements#boolean type#type matching#case comparison

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice