Question
public class Switch2
{
final static short x = 2;
public static int y = 0;
public static void main(String [] args)
{
for (int z=0; z < 3; z++)
{
switch (z)
{
case x: System.out.print("0 ");
case x-1: System.out.print("1 ");
case x-2: System.out.print("2 ");
}
}
}
}
What will be the output of the program?
public class Switch2
{
final static short x = 2;
public static int y = 0;
public static void main(String [] args)
{
for (int z=0; z < 3; z++)
{
switch (z)
{
case x: System.out.print("0 ");
case x-1: System.out.print("1 ");
case x-2: System.out.print("2 ");
}
}
}
}
Answer: Option D
Was this answer helpful ?
The case expressions are all legal because x is marked final, which means the
expressions can be evaluated at compile time. In the first iteration of the for loop
case x-2 matches, so 2 is printed. In the second iteration, x-1 is matched so 1
and 2 are printed (remember, once a match is found all remaining statements
are executed until a break statement is encountered). In the third iteration, x
is matched. So 0 1 and 2 are printed.
Was this answer helpful ?
More Questions on This Topic :
Question 2.
public class While
{
public void loop()
{
....
Question 3.
switch(x)
{
default:
System.out.println("....
Submit Solution