Given the code fragment:
Which three code fragments can be independently inserted at line nl to enable the code to print one?
A. Byte x = 1;
B. short x = 1;
C. String x = "1";
D. Long x = 1;
E. Double x = 1;
F. Integer x = new Integer ("1");
option C to be correct needs string to be converted to an integer:
int x = Integer.parseInt(“1”);
ABF
No, c is incorrect, because the cases ask for a number, not a String. Switch can take String, but here the case is a number so it won’t work. You would get a compiler error: Type mismatch: cannot convert from int to String.
public static void main(String[] args) {
Integer x =new Integer(1);
// Byte x =1;
// Short x = 1;
// String x = “1”; // not correct because with string have to put “1”
switch (x){// required: ‘char, byte, short, int, Character, Byte, Short, Integer, String, or an enum’
case 1:
System.out.println(“One”);
break;
case 2:
System.out.println(“Two”);
break;
}
}
Answer is actually: A, B, C, and F:
The question is not correct, there are four correct options.
Switch does not support boolean, long, float, double, as well as their associated wrapper classes. It only supports byte, short, int, char, and their wrapper classes, in addition to String, and enum values.
The switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).
The switch does not accept float, long, double, boolean.
ABF