nerdexam
Oracle

1Z0-808 · Question #28

Given the code fragment: ``java public class Test { public static void main(String[] args) { //line n1 Switch (X) { case 1: System.out.println("One"); break; Case 2: System.out.println("Two")…

The correct answer is A. Byte x = 1; B. short x = 1; F. Integer x = new Integer("1"). Java's switch statement accepts only byte, short, char, int, their wrapper types (Byte, Short, Character, Integer), String (since Java 7), and enums - and here the case labels are integer literals (1, 2), so X must resolve to a type compatible with int. Options A (byte) and B…

Using Operators and Decision Constructs

Question

Given the code fragment:
public class Test {
 public static void main(String[] args) { //line n1
 Switch (X) {
 case 1:
 System.out.println("One");
 break;
 Case 2:
 System.out.println("Two");
 break;
 }
 }
}
Which three code fragments can be independently inserted at line n1 to enable the code to print one?

Options

  • AByte x = 1;
  • Bshort x = 1;
  • CString x = "1";
  • DLong x = 1;
  • EDouble x = 1;
  • FInteger x = new Integer("1");

How the community answered

(45 responses)
  • A
    80% (36)
  • C
    7% (3)
  • D
    11% (5)
  • E
    2% (1)

Explanation

Java's switch statement accepts only byte, short, char, int, their wrapper types (Byte, Short, Character, Integer), String (since Java 7), and enums - and here the case labels are integer literals (1, 2), so X must resolve to a type compatible with int. Options A (byte) and B (short) are valid primitive switch types that implicitly widen to int, and F (Integer) unboxes to int at runtime, so all three allow case 1: to match and print "One".

C is wrong even though String is a valid switch type - the case labels are integer literals, not string literals ("1"), so mixing a String variable with int case labels causes a compile error. D is wrong because Long (and its primitive long) is explicitly excluded from switch - only up to int-sized types are allowed. E is wrong for the same reason: double/Double are floating-point types, which are never permitted in a switch expression.

Memory tip: Think "switch fits in an int" - any type that fits within 32 bits and is integral works (byte, short, char, int, their wrappers). Anything larger (long) or fractional (float, double) is out; String and enums are special allowed extras, but the case labels must match the variable's type.

Topics

#switch statements#auto-boxing/unboxing#type compatibility#primitive vs wrapper types

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice