tags:

views:

289

answers:

6

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.

A: 

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).

Oded
+2  A: 

You can use toString() on an class by overriding it to provide some meaningful text representation of your object.

For example you may override toString() on a Person class to return the first and last name.

Dan
+6  A: 

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).

Jeff Sternal
A: 

To string is should be used when you have a need to change a data type to a string. For built in types like int and such there string representations are what you expect. ie

  int i = 5;
  string s = i.ToString(); //s now equals "5" 

Gives you the character string "5" for most complex types and all user created types you need to overload the tostring method or you will only get the name of the class. To string allows you to use the complex formating build into .net with your own objects. you can provide complex formatters like the datetime class does to give flexibility in using your own types.

rerun
A: 
  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.

Llistes Sugra
A: 

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();
}
ponzao