ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
enum Size { S; public String toString() { return "small"; } }
// in main:
System.out.print(Size.S + " " + Size.S.name() + " ");
System.out.print(Size.valueOf("small"));
  1. A. "small S " is printed, then IllegalArgumentException is thrown
  2. B. small S small
  3. C. S S S
  4. D. "small small " is printed, then IllegalArgumentException is thrown

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

Overriding toString changes how the constant prints, but name() is final and always returns the declared identifier, and valueOf looks up by that name, so "small" is not found.

More OOP with C++ and Java questions

Exams that ask this topic