Nov
3
2011

toString Method Of Object Class In Java

In Java one always play with object.Each object has its state and behaviour.In Java every thing is an Object excluding primitives.Every exception,array,event and every thing else extends from Object.Object is the super class of all the classes in Java.Object class itself has its methods and properties.So behavior of Object class is available to all the classes of Java.Depend upon requirement sub classes can use super class method or can override super class method.

toString() method is in Object class of Java.So every class in Java can use toString method.
toString method is used to get more readable details about the object of a class.When one pass instance of a class in system.out.println() then it call toString internally.
Here below is the example of toString method.

Here is User class.

01
public class User {
02
private String firstName;
03
private String lastName;
04
 
05
public User(String fName, String lName) {
06
this.firstName = fName;
07
this.lastName = lName;
08
}
09
 
10
public String getFirstName() {
11
return firstName;
12
}
13
 
14
public void setFirstName(String firstName) {
15
this.firstName = firstName;
16
}
17
 
18
public String getLastName() {
19
return lastName;
20
}
21
 
22
public void setLastName(String lastName) {
23
this.lastName = lastName;
24
}
25
}

Here is Driver class.

1
public class Driver {
2
public static void main(String[] args) {
3
User user = new User("Jhon","Nias"); 
4
           System.out.println(user);
5
}
6
}

Output of main method is like below:
User@36d1fef1
Here first User is class name.After that a @ symbol following with a unsigned hexadecimal number which represents object’s hashcode.

Why to override toString method?
Above example shows a default out put of toString method.If one need more details about object method then he should override toString method and provide details of object in required format.
Below is the example of overridden toString method.

Overridden method:

1
@Override
2
public String toString() {
3
return "This object for user " + getFirstName() + " " + getLastName()
4
+ ".";
5
}

After overridden method the output is more meaningful.Here is output after method overriding.
This object for user Jhon Nias.

Your Suggestions Are Always Welcomed. 

Sanjay Jain

I’m a software engineer.Living in Vadodara, India. I love to work on Java and related technologies. Besides programming I like poetry, visiting new places, diary writing and hanging out with friends.

More Posts - Website

Follow Me:
TwitterFacebookLinkedIn

2 Comments+ Add Comment

  • That is good definition of toString. I think java.lang.Object class has got only methods and NOT any properties.

    • Thanks Raghavan alias Saravanan M
      Not sure about the properties in Object class.But yes there are many methods in Object class which can be used by any instance/object.

Leave a comment