Question 1
What is the output of the following program? ```java public class Main { enum Direction { NORTH, SOUTH, EAST, WEST; @Override public String toString() { return name().charAt(0) + name().substring(1).toLowerCase(); } } public static void main(String[] args) { System.out.println(Direction.NORTH + " " + Direction.SOUTH.name()); } } ```
A. North SOUTHCorrect answer
Direction.NORTH appears in a string-concatenation expression, so its toString() override is called: name().charAt(0) yields the char 'N', name().substring(1).toLowerCase() yields "orth", and char + String concatenation produces "North". Direction.SOUTH.name() is a final Enum method that bypasses toString() entirely and returns the declared identifier "SOUTH". The two parts join as "North SOUTH".
B. NORTH SOUTH
String concatenation invokes toString() on each non-String operand (JLS §15.18.1). Direction.NORTH.toString() returns "North" through the override, not the default "NORTH"; a candidate who overlooks the @Override arrives at this wrong output.
C. North South
Enum.name() is declared final in java.lang.Enum and always returns the constant's source-text identifier — "SOUTH" for SOUTH — regardless of any toString() override in the subclass. Treating name() as though it delegates to toString() is the error here.
D. Compilation fails
toString() is not final in java.lang.Enum, so an enum body may override it freely. The @Override annotation correctly identifies an existing inherited method and the code compiles without error.
Explanation
String concatenation converts each non-String operand by calling its toString() method (JLS §15.18.1), so Direction.NORTH in the expression uses the overridden toString() that title-cases the declared name, yielding "North". Enum.name() is a separate, final method that returns the constant's source identifier unchanged — no override in the enum body can affect it — so Direction.SOUTH.name() is always "SOUTH". The two values concatenate to produce "North SOUTH".