Wednesday, February 10, 2010

SCJP exercise : enum

Exercise :

public class Test {

enum Animal { "CATS", "DOGS", "ELEPHANT"};
public static void main(String [] args) {

Animal myAnimal = Animal.CATS;
if ( myAnimal == Animal.CATS) {
System.out.println("It's a CATS");
} else if (myAnimal.equals(Animal.DOGS)) {
System.out.println("It's a DOGS");
} else {
System.out.println("It's an elephant");


What is the result ? (choose one)

A It's a CATS
B It's a DOGS
C It's an elephant
D Compilation fails
E An exception is thrown at runtime

Solution :

The solution is D.There is an compilation error because the enum syntax is wrong.
It should be : enum Animal { CATS, DOGS, ELEPHANT};

No comments:

Post a Comment