Home / Java Programming / Flow Control :: Discussion

Discussion :: Flow Control

  1. 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 ");    
                 }     
             }    
         }
     } 
    

     

  2. A.

    0 def 1

    B.

    2 1 0 def 1

    C.

    2 1 0 def def

    D.

    2 1 0 def 1 def 1

    View Answer

    Workspace

    Answer : Option D

    Explanation :

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


Be The First To Comment