Java OCA OCP Practice Question 1770

Question

What will be the result of attempting to compile and run the following code?

public enum Main {
  GOOD, BETTER, BEST;//  w w w. j  av 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 because of the switch expression.
  • (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 only prints the following, when run:C
  • (e) The program compiles and only prints the following, when run: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