java.lang.Object is the super class for all the Java objects. i.e.; every class extends to java.lang.Object by default. So, all the methods that are available in java.lang.Object class will be available to our class that we've defined. One of the method defined in java.lang.Object class is toString().

toString()

toString() is meant to convert an object into a string representation. You would argue why an object has to be converted into string representation? Answer is very simple, JVM uses a string representation of an object when concatenating or when used with System.out.println() statement. Just observe below program


public class Employee
{
int id;
String name;

public static void main(String args[])
{
Employee emp = new Employee();
System.out.println(emp);
}
}

Just guess what will be the output. JVM invokes a toString() method on emp object. And since the toString() method has already been implemented in java.lang.Object, output will be the object name@hash code (This is how Javasoft implemented in java.lang.Object class).

Output

>java Employee
Employee@19821f

Overriding toString method

We can override toString method in the above class to achieve customized string representation of Employee class object. We can just print the employee id and employee name values. As you know, when overriding we should follow exact signature that has been defined in the super class.

Syntax

public String toString()
{
//code to return the string representation
}
Employee.java

public class Employee
{
int id;
String name;

public Employee(int id, String name)
{
this.id = id;
this.name = name;
}

public String toString()
{
return "Employee[id="+id+", name="+name+"]";
}

public static void main(String args[]) throws Exception
{
Employee e = new Employee(1, "Santhosh Reddy");
System.out.println(e);
}

public void setId(int id)
{
this.id = id;
}

public int getId()
{
return id;
}

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

public String getName()
{
return name;
}
}
Output

>java Employee
Employee[id=1, name=Santhosh Reddy]