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








Question

What will be printed out when the following code is executed?

switch (5) { 
    case 0: 
       System.out.println("zero"); 
       break; 
    case 1: 
       System.out.println("one"); 
    default: 
       System.out.println("default"); 
    case 2: 
       System.out.println("two"); 
} 
  1. one
  2. default and two
  3. one, two, and default
  4. Nothing, a compile-time error is generated




Answer



B

Note

The default case can be positioned anywhere within the switch.

Only the first case has the break statement.

It is OK to use constants for switch statements.

public class Main {
  public static void main(String[] args) {
    switch (5) {// w  w w.  j  a  v  a 2  s .  c  o  m
    case 0:
      System.out.println("zero");
      break;
    case 1:
      System.out.println("one");
    default:
      System.out.println("default");
    case 2:
      System.out.println("two");
    }
  }
}

The code above generates the following result.