toString() method
This method returns the string representation of the object which invokes this method.
This method is mainly used to represent the java object into a meaningful string.
This is mostly required while logging the object information into logger file.
This method is defined in Object class and any other class in java(apparently subclass of Object class) can override this method.
Signature of this method
- public String toString()
public String toString()
If we don’t override this method in our class, then it returns the Object’s address in hexadecimal
format along with class name.
Example:
- public class Employee1{
- String name;
- int age;
- public static void main(String args[])
- {
- Employee1 e = new Employee1 ();
- e.name=”john”;
- e.age=20;
- System.out.println(e);
- }
- }
public class Employee1{ String name; int age; public static void main(String args[]) { Employee1 e = new Employee1 (); e.name=”john”; e.age=20; System.out.println(e); } }
If we override this method in our class, then it returns the value provided in overridden toString() method
Example
- public class Employee2{
- String name;
- int age;
- public static void main(String args[])
- {
- Employee2 e = new Employee2 ();
- e.name=”john”;
- e.age=20;
- System.out.println(e); //same as System.out.println(e.toString());
- }
- public String toString()
- {
- return "name->"+name+” “+”age->”+age;
- }
- }
public class Employee2{ String name; int age; public static void main(String args[]) { Employee2 e = new Employee2 (); e.name=”john”; e.age=20; System.out.println(e); //same as System.out.println(e.toString()); } public String toString() { return "name->"+name+” “+”age->”+age; } }
As we can see in the above example that, Printing an object gives a meaningful string which represent the state of an Employee object.
- System.out.println(e)
System.out.println(e)
This is same as
- System.out.println(e.toString());
System.out.println(e.toString());
Whenever we print any object of any class, its toString() method will be called
We can also call this explicitly for String class as below
- String str=”java”;
- System.out.println(str.toString());
String str=”java”; System.out.println(str.toString());
This is same as
- String str=”java”;
- System.out.println(str);
String str=”java”; System.out.println(str);
Since String class has already overridden the toString() method, it returns the string value rather than hexadecimal
address of object.
Note :
Its good practice to override the toString() method in all our model classes which represent the state so that we can print them in the logger wherever required just by using object.