Java OCA OCP Practice Question 1648

Question

What will be the result of compiling and running the following code?.

public enum Main {
 GOOD, BETTER, BEST;//from  w  ww . j a v  a  2s  . c  o m

 public char getGrade() {
   char grade = '\u0000';
   switch(this){
     case GOOD:   grade = 'C'; break;
     case BETTER: grade = 'B'; break;
     case BEST:   grade = 'A'; break;
   }
   return grade;
 }

 public static void main (String[] args) {
   System.out.println(GOOD.getGrade());
 }
}

Select the one correct answer.

  • (a) The program will not compile, as the switch expression is not compatible with the case labels.
  • (b) The program will not compile, as enum constants cannot be used as case labels.
  • (c) The case labels must be qualified with the enum type name.
  • (d) The program compiles, and when run, prints: C
  • (e) The program compiles, and when run, prints: GOOD
  • (f) None of the above.


(d)

Note

Enum constants can be used as case labels and are not qualified with the enum type name in the case label declaration.

The switch expression is compatible with the case labels, as the reference this will refer to objects of the enum type Main, which is the type of the case labels.

The call to the method getGrade() returns a char value, which in this case is 'C'.




PreviousNext

Related