In String toString()
method returns this
and when i pass it System.out.println()
it prints the content of the String
. It is c
The toString
method, defined on Object
in Java is responsible for converting the object to a String representation. Since String
is already a String, the toString
method simply returns itself.
and when i pass it System.out.println() it prints the content of the String
In fact, when you pass a String
to System.out.println
you don't go through toString
anyway. The System.out
refers to a PrintStream
object which has a method that accepts String
s immediately:
public void println(String x)
Prints a String and then terminate the line.
The contract of toString is to return a string representation of the object:
public String toString()
Returns a string representation of the object. In general, the
toString
method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
Since String
happens to be a String
it can return itself (this
)!