nerdexam
Oracle

1Z0-811 · Question #27

Given the code fragment: // line n1 switch (var) { case "1": System.out.println ("one"); break; } Which code fragment, when inserted at line n1, enables the code to print one?

The correct answer is B. String var = "1". Option B works because Java's switch statement supports String types (since Java 7), and the case label "1" is a String literal - so declaring String var = "1" produces an exact match, printing one. Why the distractors fail: A (char var = '1'): A char switch requires char case…

Data Types and Operators

Question

Given the code fragment: // line n1 switch (var) { case "1": System.out.println ("one"); break; } Which code fragment, when inserted at line n1, enables the code to print one?

Options

  • Achar var = '1';
  • BString var = "1";
  • Cint var = 1;
  • DString var = 1;

How the community answered

(56 responses)
  • A
    9% (5)
  • B
    86% (48)
  • C
    4% (2)
  • D
    2% (1)

Explanation

Option B works because Java's switch statement supports String types (since Java 7), and the case label "1" is a String literal - so declaring String var = "1" produces an exact match, printing one.

Why the distractors fail:

  • A (char var = '1'): A char switch requires char case labels like case '1':, not String literals like case "1": - this causes a compile error.
  • C (int var = 1): An int switch requires numeric or char case labels; case "1": is a String literal and is incompatible - compile error.
  • D (String var = 1): Assigning the integer 1 directly to a String variable is a type mismatch - Java won't implicitly convert an int to a String.

Memory tip: Match the type of the variable to the type of the case labels. The case here uses double quotes ("1"), which is a String literal - so the variable must also be a String. Single quotes = char, no quotes = numeric.

Topics

#switch statement#String literals#type matching#primitive vs reference types

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice