Java OCA OCP Practice Question 365

Question

What will the following code print when run?

public class Main {
   public void switchString(String input) {
      switch (input) {
      case "a":
         System.out.println("apple");
      case "b":
         System.out.println("bat");
         break;/*from   w w  w. j a v a  2s  . c o  m*/
      case "B":
         System.out.println("big bat");
      default:
         System.out.println("none");
      }
   }

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

Select 1 option

A. bat 
   big bat 
B. big bat 
   none 
C. big bat 
D. bat 
E. The code will not compile. 


Correct Option is  : B

Note

Since there is a case condition that matches the input string "B".

That case statement will be executed directly.

This prints "big bat".

Since there is no break after this case statement and the next case statement, the control will fall through the next one (which is default : ) and so "none" will be printed as well.

Note that "b" and "B" are different strings. "B" is not equal to "b".

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




PreviousNext

Related