Default String representation of Object

I have seen many questions on StackOverFlow where users comes up with the output which contains some gibberish(at least they feel so) text like abc@195a09c. So, let’s see what this output actually means.

First of all this out put is made of three things for the Object on which toString method has been called (externally or internally).

  • Fully qualified name (i.e. java.lang.Object, com.in.my.Car)
  • @
  • Hexadecimal representation of hash code

Note that,

Hash Code method in Java digest the data stored in the object and provide 32-bit signed integer (hash) value.

Consider following example of class Car.

class Car {

	private String name;
	
	private int price;

	public Car(String name, int price) {
		this.name = name;
		this.price = price;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

}

public class DefaultToString {

	public static void main(String[] args) {
		Car car = new Car("Oddy", 250000000);
		System.out.println(car);
	}
}

Above code will give you String something like Car@1db9742 in your console. Now this does not convey anything about the Car Object which has name and price in it. This String is created by the Parent of your Car which is Object, Object class will have a method named toString which is giving you this output. So, if you don’t want to use the default implementation of the toString method of Object class you need to declare your own method in your Car class like this.

@Override
public String toString() {
	return name + " worth " +price + "$";
}

After adding this method in your Car, just run the DefaultToString class again and you will have following output.

Oddy worth 250000000$

As you can see now you have changed the default behaviour of toString for your Car class by adding toString method. When you try to print Car Object and your Car does not have toString implementation it will call the roString of parent class which is Object. The default toString method looks like this,

public String toString() {
   return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

So, when you don’t specify toString method for your own class and you try to print your instance, your code will internally call above toString method to print your Object.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s