What will be the output of the program? public class TestObj { public static…
2023
What will be the output of the program?
public class TestObj
{
public static void main (String [] args)
{
Object o = new Object() /* Line 5 */
{
public boolean equals(Object obj)
{
return true;
}
} /* Line 11 */
System.out.println(o.equals("Fred"));
}
}- A.
It prints "true".
- B.
It prints "Fred".
- C.
An exception occurs at runtime.
- D.
Compilation fails
Attempted by 4 students.
Show answer & explanation
Correct answer: D
In Java, a local variable declaration is one single statement, and every statement must end with a semicolon. When the initializer is an anonymous class instantiation of the form new SomeType() { ... }, the declaration does not close at the anonymous class body's final closing brace — it closes only at the semicolon that must follow that brace.
Applying this to the code:
Line 5 opens the declaration: Object o = new Object() { … begins an anonymous subclass of Object assigned to o.
The anonymous class body runs from the opening brace on line 5 through the closing brace on line 11, overriding equals(Object) to unconditionally return true.
The declaration statement that started on line 5 is still open at that closing brace — Java requires a semicolon right after it to terminate the statement.
No semicolon follows the closing brace on line 11, so the compiler reports a syntax error at that point and TestObj never finishes compiling.
Cross-check: add a semicolon right after the closing brace on line 11 and the class compiles cleanly. Then o.equals("Fred") calls the anonymous subclass's overridden equals(Object), which unconditionally returns true, so System.out.println would print true. That confirms the only problem with the code exactly as written is the missing statement-terminating semicolon — not the equals() logic and not anything that could throw at runtime.