OCA Java SE 8 Mock Exam 2 - OCA Mock Question 35








Question

What's the output of the following code?

public class Main {
  public static void main(String args[]) {
    byte foo = 120;
    switch (foo) {
    default:
      System.out.println("default");
      break;
    case 2:
      System.out.println("2");
      break;
    case 120:
      System.out.println("120");
    case 121:
      System.out.println("121");
    case 127:
      System.out.println("127");
      break;
    }
  }
}

             a  120 
                121 
                127 

             b  120 

             c  default 
                2 

             d  120 
                121 
                127 
                default 




Answer



A

Note

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

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

public class Main {
  public static void main(String args[]) {
    byte foo = 120;
    switch (foo) {
    default://from www.  j  a  va  2 s  .com
      System.out.println("default");
      break;
    case 2:
      System.out.println("2");
      break;
    case 120:
      System.out.println("120");
    case 121:
      System.out.println("121");
    case 127:
      System.out.println("127");
      break;
    }
  }
}