Which statement is true about the following code fragment?
1. int j = 2; //from w w w . j av a 2s . c om 2. switch (j) { 3. case 2: 4. System.out.println("value is two"); 5. case 2 + 1: 6. System.out.println("value is three"); 7. break; 8. default: 9. System.out.println("value is " + j); 10. break; 11. }
switch()
construct, could be any of byte, short, int, or long. D.
A is incorrect because the code is legal despite the expression at line 5; the expression itself is a constant.
B is incorrect because it states that the switch()
part can take a long argument.
Only byte, short, char,String, enum, and int are acceptable.
The output results from the value 2 like this: first, the option case 2: is selected, which outputs value is two.
There is no break statement between lines 4 and 5, so the execution falls into the next case and outputs value is three from line 6.
The default: part of a switch()
is executed only when no other options have been selected, or if no break precedes it.
The output consists only of the two messages listed in D.