Flow Control

Q1: 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 < 4; z++) 
        {
            switch (z) 
            {
                case x: System.out.print('0 ');
                default: System.out.print('def ');
                case x-1: System.out.print('1 ');  
                            break;
                case x-2: System.out.print('2 ');
            }
        }
    }
}

A 2 1 0 def def

B 2 1 0 def 1

C 2 1 0 def 1 def 1

D 0 def 1

ANS:A - 0 def 1

When z == 0 , case x-2 is matched. When z == 1, case x-1 is matched and then the break occurs. When z == 2, case x, then default, then x-1 are all matched. When z == 3, default, then x-1 are matched. The rules for default are that it will fall through from above like any other case (for instance when z == 2), and that it will match when no other cases match (for instance when z==3).



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.