when to use toString() method

This may sound very basic... can someone please explain the use of the toString() method and when to effectively use this?

Have done a search on google but could not find any good resource.


Solution 1:

In most languages, toString or the equivalent method just guarantees that an object can be represented textually.

This is especially useful for logging, debugging, or any other circumstance where you need to be able to render any and every object you encounter as a string.

Objects often implement custom toString behavior so that the method actually tells you something about the object instance. For example, a Person class might override it to return "Last name, First name" while a Date class will show the date formatted according to some default setting (such as the current user interface culture).

Solution 2:

There are several situations in which one would wish to override the toString method of a class (most of which are already mentioned in the existing answers), but one of the most common situations in which I have needed to explicitly call toString on an object is when using StringBuilder to construct a String.

public String createString(final String str) {
  final StringBuilder sb = new StringBuilder(str);
  sb.append("foo");
  sb.append("bar");
  return sb.toString();
}

Solution 3:

  1. You want to display an object and don't want to check if it is null before.
  2. You want to concat Strings and not thinking about a special attribute, just provide a default one to the programmer.

Thus:

out.println("You are " + user);

will display "You are null" or "You are James" if user is null or toString displays "James" for this (existent) instance.

Solution 4:

Assuming .NET or Java:

In general, you should overload ToString() when you want a textual representation of your class (assuming it makes sense for your class).