toString() method demystified

Posted: August 5, 2011 in Java
Tags: ,

Suppose you have an object of a class.

What do we see if we try to print this object?

MyClass obj = new MyClass();


It prints a String in the following format

ClassName+@+a hex code version of the object’s hashcode.

eg: MyClass@19821f

The java Object class has a toString() method.

Our classes have to override this toString() method to return a more meaningful representation that is easy to read and understand.

Example :

public class MyClass {

private String name;
private int age;

// setters and getters for the 2 fields mentioned above.

public String toString() {
return “name = “+name+” and age = “+age;

Now if we try to printSystem.out.print(obj);

we get the following output

name = John and age = 25


Leave a Reply

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

You are commenting using your 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