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…
Question
Options
- Achar var = '1';
- BString var = "1";
- Cint var = 1;
- DString var = 1;
How the community answered
(56 responses)- A9% (5)
- B86% (48)
- C4% (2)
- D2% (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'): Acharswitch requires char case labels likecase '1':, not String literals likecase "1":- this causes a compile error. - C (
int var = 1): Anintswitch requires numeric or char case labels;case "1":is a String literal and is incompatible - compile error. - D (
String var = 1): Assigning the integer1directly to aStringvariable is a type mismatch - Java won't implicitly convert anintto aString.
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
Community Discussion
No community discussion yet for this question.