What is the output?

interface TestA { String toString(); }
 public class Test {
 public static void main(String[] args) {
  System.out.println(new TestA() {
  public String toString() { return "test"; }
 });
 }
}
  1. test

  2. null

  3. Compilation fails because of an error in line 1.

  4. An exception is thrown at runtime.


Correct Option: A
Explanation:

To solve this question, the user needs to understand Java syntax, specifically the concepts of interfaces, anonymous inner classes, and the toString() method.

In the given code, an anonymous inner class is created that implements the TestA interface. This inner class overrides the toString() method from the Object class and returns the string "test".

Now let's go through each option and explain why it is right or wrong:

A. test: This option is correct. When the toString() method is called on the anonymous inner class object, it returns the string "test". This is the output that will be printed to the console.

B. null: This option is incorrect. The toString() method is overridden in the anonymous inner class to return the string "test", not null. Therefore, the output will not be null.

C. Compilation fails because of an error in line 1: This option is incorrect. There is no error in line 1. The interface TestA is defined correctly.

D. An exception is thrown at runtime: This option is incorrect. There is no exception thrown in the given code. The code will compile and run without any exceptions.

The Answer is: A. test

Find more quizzes: