1

In String toString() method returns this and when i pass it System.out.println() it prints the content of the String. It is confusing for me how is that happening. can comeone explain please.

public String toString() { return this; }

Thanks.

George
  • 255
  • 3
  • 18

2 Answers2

9

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.

Chris
  • 22,923
  • 4
  • 56
  • 50
  • May also be helpful to know that the keyword `this` refers to the current object. –  Nov 26 '11 at 12:40
6

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 Strings 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)!

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • And in fact, as your comment demonstrates, the contract for the toString method is very loose. The implementation can vary wildly. Many classes return just the class name and instance ID. The String class returns the string value. This means that the toString method is generally useful only for debugging. One important exception to this is the StringBuffer's toString method. – dnuttle Nov 26 '11 at 13:02