Debugging With the Java Object’s toString() Method

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

See also  11 Effective Keyword Research Tools and Techniques

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist