Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Tuesday, September 29, 2009

The To String method

The toString() Method Override toString() when we want to read something meaningful about the objects of our class. Code can call toString() on our object when it wants to read useful details about our object.

To be more clear, Now when we pass an object reference to the System.out.println() method, and for example, the object's toString() method is called as follows,

public class ClassA {
public static void main (String [] args) {
ClassA classA = new ClassA();
System.out.println(classA);
}
}


then, Running the ClassA class gives us the following output,

% Java ClassA
ClassA@10b62c9


The above output is what we get when we don't override the toString() method of class Object. It gives us the class name (at least that's meaningful) followed by the @ symbol, followed by the unsigned hexadecimal representation of the object's hashcode.

Trying to read this output might motivate us to override the toString() method in our classes, for example,

public class ClassA {
public static void main (String[] args) {
ClassB classB = new ClassB("Test the toString method", new Date());
System.out.println(classB);
}
}
class ClassB {
Date data1;
String data2;
ClassB(String data2, Date data1) {
this.data1 = data1;
this.data2 = data2;
}
public String toString() {
return ("The main aim of this program is to " + data2 +
". This program was written on " + data1);
}

}

The output of this would be a bit more readable:

% Java ClassA
The main aim of this program is to Test the toString method. This program was written on Tue Sep 29 10:26:59 IST 2009


For your Information, Some people refer the toString() method as the "spill-your-guts method," since the most common implementations of toString() simply tell us the object's state.

No comments: