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 = [email protected]

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 MyClass2.   {3.     int myNum_ = 100;4.     String myString_ = "This is my class !!! ";5. 6.     // Constructors and other code here7. 8.     public String toString ()9.     {10.       StringBuffer sb = new StringBuffer();11. 12.       sb.append("
======= Begin MyClass object =======
");13.       sb.append("
myNum_ = " + myNum_);14.       sb.append("
myString_ = " + myString_);15.       sb.append("
======= End MyClass object ========
");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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: