Computer Science, asked by chaikr, 10 months ago

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


Select one:

a. Compilation fails.

b. j = 0

c. j = -1

d. j = 1​

Answers

Answered by ridhimakh1219
4

The correct option is a. Compilation fails.

Explanation:

Output of given program:

Compilation failed due to following error(s).

Main.java:4: error: : expected

   case 0, 1: j = 1; /* Line 4 */

Main.java:4: error: ';' expected

   case 0, 1: j = 1; /* Line 4 */

Main.java:4: error: illegal start of expression

   case 0, 1: j = 1; /* Line 4 */

Correct Program

public class Main{

   public static void main(String[] args) {

   int i = 1, j = -1;

   switch (i)  {

   case 0: j = 1;

   case 1: j = 1;  // case match as i = 1

   case 2: j = 2;

   default: j = 0;

    }

    System.out.println("j = " + j);

}

}

Output

j = 0

Note

The break statement is not written at the end of each case in switch then all consecutive case statements get executed after matching i with case 1 till the default case(end of switch) thus j becomes 0.

Similar questions