Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Feb 1, 1999

Debugging With the Java Object's toString() Method

Java's Object class provides a method called toString() that returns the string representation of the object on which it is called. The method signature for toString() is:
 
public String toString ();
The toString() method is useful for debugging. By default, when an object is printed out in a print stream like System.out, the toString() method of the object is automatically called. For example, in the following code, the string representation of myObject is printed out:
 
MyClass myObject = new MyClass();
System.out.println"myObject=" + myObject);
The problem with just printing out myObject is that the default toString() method of the supeclass (Object) is called unless myObject overrides the toString() method. As a result, if myObject does not override the toString() method, just the reference value of myObject (not its contents) is printed out. For example, the previous call may print out something like:
 
myObject = MyClass@1ee80a
What you'd like to see is a printout of the contents of the object, not the object's reference. You can achieve this by overriding the default toString() method inside MyClass to return the contents of the instance of MyClass:
 
1.   public MyClass
2.   {
3.     int myNum_ = 100;
4.     String myString_ = "This is my class !!! ";
5. 
6.     // Constructors and other code here
7. 
8.     public String toString ()
9.     {
10.       StringBuffer sb = new StringBuffer();
11. 
12.       sb.append("\n======= Begin MyClass object =======\n");
13.       sb.append("\nmyNum_ = " + myNum_);
14.       sb.append("\nmyString_ = " + myString_);
15.       sb.append("\n======= End MyClass object ========\n");
16. 
17.       return (new String(sb));
18.     }
19.   }
The toString() method on Lines 8-18 overrides the superclass's toString() method. The contents (attributes/state) of MyClass are filled into the StringBuffer sb in Lines 12-15. On Line 17, a new String object is constructed from sb and returned to the calling method. If the object myObject is now constructed and then printed out, you'll get meaningful output that displays the contents of the class.
Ajit Sagar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date