Q: How this print statement works? interface TestA {
    String toString();
}

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

This will print test as output.


*

*Can anyone explain how this works? 

*When I change the method name toString() as printString, it will print
only a memory address.Explain how it works.


A: The code:
new TestA() {
    public String toString() {
        return "test";
    }
}

is an anonymous class, which can be thought of as a sort of on-the-fly class definition and instantiation.  This class definition implements a toString() method, which happens to return the string test.  This anonymous class, when passed to System.out.println, then would result in test being printed.
If you change TestA#toString to TestA#printString, then there is no longer an implementation of toString, and the default behavior of Java is to print the hashcode.

A: The Object class defines a method toString() that returns a "String representation" of the object. The base method returns the class name and hash code.
It's generally a good idea to override the toString() method and return a better representation.
There are many things in Java that will call an object's toString() method. System.out.println() is one of them. Another common one is the + operator when you are concatenating to a String (like "hello " + myObj).
In your first example, you're creating an anonymous inner class instance of the TestA interface, and overriding toString(). That means that System.out.println() prints the "test" String you defined.
If you rename the method, now you just get the default Object implementation of toString(), and get the "memory address" version.

A: Object is the super class of all the classes in Java and it has a method toString() which prints the object reference.
If you print any object, java compiler internally invokes the toString() method on the object.
Here you are printing new TestA() so it is calling toString method internally, which you have overridden to print test.
But when you change the name of the method then it calls the toString implementation of Object class.
