Saturday, 5 November 2011

Sun Certified Java Programmer (SCJP)-9

What will be printed out if you attempt to compile and run the following code?

int i = 3;
switch (i)
{


default:


System.out.println("default");


case 0:


System.out.println("zero");


case 1:


System.out.println("one");
break;


case 2:


System.out.println("two");


}


Choices:

  • A. default

  • B. default, zero, one

  • C. Compiler error

  • D. No output displayed


Correct choice:  B

Explanation:

Although it is normally placed last, the default statement does not have to be placed as the last option in the case block. Since there is no case label found matching the expression, the default label is executed and the code continues to fall through until it encounters a break statement.

1 comment: