Java OCA OCP Practice Question 2439

Question

What's the output of the following code?

public class Main3 { 
    public static void main(String args[]) { 
        byte foo = 120; 
        switch (foo) { 
            default: System.out.println("abc"); break; 
            case 2: System.out.println("e"); break; 
            case 120: System.out.println("ejava"); 
            case 121: System.out.println("enum"); 
            case 127: System.out.println("guru"); break; 
        } /*  w  ww .java  2s  .  c om*/
    } 
} 
a  ejava //from   w w  w.  ja v a 2  s  .  co m
   enum 
   guru 

b  ejava 

c  abc 
   e 

d  ejava 
   enum 
   guru 
   abc 


a

Note

For a switch case construct, control enters the case labels when a matching case is found.

The control then falls through the remaining case labels until it's terminated by a break statement.

The control exits the switch construct when it encounters a break statement or it reaches the end of the switch construct.

In this example, a matching label is found for case label 120.

The control executes the statement for this case label and prints ejava to the console.

Because a break statement doesn't terminate the case label, the control falls through to case label 121.

The control executes the statement for this case label and prints enum to the console.

Because a break statement doesn't terminate this case label also, the control falls through to case label 127.

The control executes the statement for this case label and prints guru to the console.

This case label is terminated by a break statement, so the control exits the switch construct.




PreviousNext

Related