Java OCA OCP Practice Question 1521

Question

What will the following code print when run?

public class Main  { 

    public void m (String input){ 
        switch (input){ 
            case "a"  : System.out.println ( "apple" ); 
            case "b"  : System.out.println ( "bat" ); 
                break; 
            case "c"  : System.out.println ( "cat" );                 
            default  : System.out.println ( "none" ); 
         } //from  ww  w.  ja  v  a2 s  .c  o  m
     } 

    public static void main (String [] args) throws Exception  { 
        Main tc = new Main (); 
        tc.m ("c"); 
     } 
} 

Select 1 option

A. apple //from w  w w  . j  a  v  a2s .c  om
   cat 
   none 

B. apple 
   cat 

C. cat 
   none 

D. cat 
 


Correct Option is  : C

Note

In the JDK 7 release, you can use a String object in the expression of a switch statement:

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive.

The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.




PreviousNext

Related