Overriding the toString() method in Object class

The toString() method in the Object class is used to display some information regarding any object. If any code needs some information of an object of a class, then it can get it by using this method. The toString() method of an object gets invoked automatically, when an object reference is passed in the System.out.println() method. The following code illustrates this,

also read:

ToStringMethodTest.java

public class ToStringMethodTest {
	private String companyName;
	private String companyAddress;
	public ToStringMethodTest(String companyName, String companyAddress) {
		this.companyName = companyName;
		this.companyAddress = companyAddress;
	}
	public static void main(String[] args) {
		ToStringMethodTest test = new ToStringMethodTest("ABC private Ltd","10, yy Street, CC Town");
		System.out.println(test);
	}
}

This output seems a bit weird. If we analyze it closely, we can find that the output is nothing but the Class name ToStringMethodTest and then the ‘@’ symbol is followed by 18d107f which is the hashcode of the object.

In case we would like to display some meaningful details of an object, we can override the toString() and thereby achieve it. Consider the following code,
ToStringMethodTest.java

public class ToStringMethodTest {
	private String companyName;
	private String companyAddress;
	public ToStringMethodTest(String companyName, String companyAddress) {
		this.companyName = companyName;
		this.companyAddress = companyAddress;
	}
	public static void main(String[] args) {
		ToStringMethodTest test = new ToStringMethodTest("ABC private Ltd","10, yy Street, CC Town");
		System.out.println(test);
	}

	public String toString() {
		return ("Company Name: " + companyName + "n" +
		"Company Address: " + companyAddress);
	}
}

The result of the above code is,

Company Name: ABC private Ltd
 Company Address: 10, yy Street, CC Town

What we have just now seen is just a sample of how a meaningful override of the toString() method would prove to be of great use in displaying an object’s information when we try printing an object using the System.out.println statement during debugging process.

also read:

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. data ss

  2. you forgot to add @override annoation in the toString method implementation. See my code example: toString method implementation

Trackbacks

  1. […] this article to we will see how to override the toString method and what are the best practices in Java. Java provides a default implementation for the method […]

Speak Your Mind

*