Java OCA OCP Practice Question 2160

Question

What is the output of the following application?.

1:  package mypkg; 
2:  interface Printable {String getValue();} 
3:  enum COLORS implements Printable { 
4:     red { /*from w  w  w .  ja va  2 s  .  c om*/
5:        public String getValue() {return "FF0000";} 
6:     }, green { 
7:        public String getValue() {return "00FF00";} 
8:     }, blue { 
9:        public String getValue() {return "0000FF";} 
10:    } 
11: } 
12: class Book { 
13:    static void main(String[] pencils) {} 
14: } 
15: final public class ColoringBook extends Book { 
16:    final void paint(COLORS c) { 
17:       System.out.print("Painting: "+c.getValue()); 
18:    } 
19:    final public static void main(String[] crayons) { 
20:       new ColoringBook().paint(COLORS.green); 
21:    } 
22: } 
  • A. Painting: 00FF00
  • B. One line of code does not compile.
  • C. Two lines of code do not compile.
  • D. Three lines of code do not compile.
  • E. The code compiles but prints an exception at runtime.
  • F. None of the above


A.

Note

The code compiles and runs without issue, making Option A the correct answer.

Enums are usually named like classes and have enum values that are all uppercase.

While a format like Colors.RED or Colors.GREEN is the common convention, alternate formats like COLORS.blue do compile.

Next, note the enum properly implements the Printable interface even though there's no enum-level method, with each value having its own implementation.

Also, line 10 does not end with a semicolon (;).

Because there are no methods or constructors defined outside the value list, a semicolon (;) is not required.

The enum class and the rest of the application compile without issue, printing Painting: 00FF00 at runtime.




PreviousNext

Related