Machine-translated by Google. Questions are authored in English.
Top

Discussion

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); 

  • A.j = -1
  • B.j = 0
  • C.
    j = 1
  • D.Compilation fails.

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.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.