The toString() method solves so many question that we see these days in the forums, and it is crucially important to understand it. It is a method that is defined in the Object class and thus, every object has one, however, it prints out, for the most part, meaningless information. Let me show you an example. I’m going to write a simple class that stores the name and age of somebody:
public class Person {
private int age;
private String name;
public Person() {
this (0, "");
}
public Person(int i, String string) {
age = i;
name = string;
}
public static void main(String[] args) {
Person p = new Person(40, "John Doe");
System.out.println(p);
}
}
This program prints p as Person@3e25a5 which is the default implementation of toString(). This output is the class name (Person) and the hash code that represents that object. This is because under the covers System.out.println() calls an object’s toString() method implicitly.
However, this output is virtually meaningless. No end user wants to know what the class name or the hash code is. They want to know what the object IS. In that case, they will want to know the age and name of the Person object that they have. You only have to make one change – add a toString() method to whatever class that you want to describe. Following is an improved version of the above program with a toString() method added:
public class Person {
private int age;
private String name;
public Person() {
this (0, "");
}
public Person(int i, String string) {
age = i;
name = string;
}
@Override
public String toString() {
return "Name: " + name + " \nAge: " + age + "\n\n";
}
public static void main(String[] args) {
Person p = new Person(40, "John Doe");
System.out.println(p);
}
}
The output here is much nicer. This time it nicely tells the Name and the Age of the Person:
Name: John Doe
Age: 40
So, what uses does this have? Loads. If you EVER need a String representation of any object for any purpose, toString() is the easiest way to go. It can perform any number of computations – as long as it returns a String in the end. This makes it easier for objects that have arrays to return their values. It also makes debugging a lot easier and makes your objects easier to understand. Remember that if you ever need the old implementation with the addition of something new, you can always add super.toString() to the returned String.
Thanks for reading this short (yet important) tutorial, and I hope that you learned something!









MultiQuote







|