ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
enum Dir { N, E, S, W }
// in main:
System.out.print(Dir.values()[2] + " " + Dir.valueOf("W").ordinal() + " ");
System.out.print(Dir.valueOf("w"));
  1. A. "S 3 " is printed, then IllegalArgumentException is thrown
  2. B. S 3 W
  3. C. "E 4 " is printed, then IllegalArgumentException is thrown
  4. D. S 3 null

Correct answer: A. "S 3 " is printed, then IllegalArgumentException is thrown

values() is in declaration order (index 2 = S) and ordinals start at 0 (W = 3). valueOf is case-sensitive and throws IllegalArgumentException for a name that is not a constant; it never returns null.

More OOP with C++ and Java questions

Exams that ask this topic