Java OCA OCP Practice Question 218

Question

Given:

public class Main {
  public static void main(String[] args) {
    String o = "-";
    switch("FRED".toLowerCase().substring(1,3)) {
      case "yellow":
        o += "y";
      case "red":
        o += "r";
      case "green":
        o += "g";
    }/*www.jav  a 2  s.  c o m*/
    System.out.println(o);
  }
 }

What is the result?

  • A. -
  • B. -r
  • C. -rg
  • D. Compilation fails
  • E. An exception is thrown at runtime


A is correct.

Note

As of Java 7 the code is legal, but the substring() method's second argument is exclusive.

If the invocation had been substring(1,4), the output would have been -rg.

We hope you won't have too many exam questions that focus on API trivia like this one.

If you knew the switch was legal, give yourself "almost full credit."




PreviousNext

Related