2

Possible Duplicates:
What are the original reasons for ToString() in Java and .NET?
when to use toString() method

what is main use of toString() in java

Community
  • 1
  • 1
user347725
  • 39
  • 1
  • 2
  • See [What are the original reasons for ToString() in Java and .NET?](http://stackoverflow.com/questions/2307896/what-are-the-original-reasons-for-tostring-in-java-and-net) – Matthew Flaschen May 22 '10 at 09:56
  • Or http://stackoverflow.com/questions/2329168/when-to-use-tostring-method – Artelius May 22 '10 at 10:47

4 Answers4

17

As the javadoc says:

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.

You can use this for:

  • logging
  • debugging
  • representing in UI

etc.

However, it is advisable that you use it only for internal purposes, like logging and debugging.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    +1 especially for "it is advisable that you use it only for internal purposes, like logging and debugging". *Effective Java* (I forget which item exactly) gives some good examples as to why this is the case. – Jonik May 22 '10 at 11:26
  • 1
    It pains me when StringBuffer or StringBuilder breaks this principle... – Vincent Robert May 22 '10 at 11:35
  • @Vincent, fair point. But there it's a different semantics, perhaps it should've been `buildString()` instead of `toString()` – Bozho May 22 '10 at 11:43
  • toString() should not be used for representation in UI. Representation in a UI is more often than not dependent on context (such as user Locale). Also, what is useful for logging is often very different than what is useful (or understandable) for a user. – Auke te Winkel May 11 '16 at 11:35
2

The main use of toString() is allowing arbitrary objects to be printed or logged.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
1

In short, you come up with a String representation of your class, so you'll see meaningful values in your logs or when debugging instead of the default YourClass@38c313. This representation is completely arbitrary.

For details, have a look at Item 10 in Effective Java, it has a couple of pretty good advices.

candiru
  • 4,424
  • 2
  • 22
  • 16
0

Just to add, sometimes it is useful to convert some object to a textual representation, and then define a constructor which can create an object out of this textual representation, something like

public Foo(String textualRep) {

}

I've seen this approach somewhere in used in the JDK but can't remember where.

helpermethod
  • 59,493
  • 71
  • 188
  • 276