1
visibility

Predict the output if p=1

int a=1,b=2,c=3;
switch(p)
{
    case 1: a++;
    case 2: ++b;
            break;
    case 3: c--;
}
System.out.println(a+","+b+","+c);

 

  • 1,2,3

  • 1,3,3

  • 2,2,3

  • 2,3,3

When p is 1, case 1 is matched. a++ increments value of a to 2. As there is no break statement, fall through to case 2 happens. ++b increments b to 3. break statement in case 2 transfers program control to println statement and we get the output as 2,3,3.