What will be the output of the program?
int i = 1, j = -1;
switch (i)
{
case 0, 1: j = 1; /* Line 4 */
case 2: j = 2;
default: j = 0;
}
System.out.println("j = " + j);
Answer: D
Correct answer: Compilation fails.
A classic switch statement takes one constant per case label, so case 0, 1: is a syntax error - the way to match two values is to write two labels one after the other, case 0: case 1:, relying on fall-through. The comma form was introduced only with the switch expressions of Java 14 and belongs to the arrow syntax, not to this one. Nothing runs, so j is never assigned.
Please log in or register to report this question.