Java toString() Method

The Java toString() method represents Java objects as human-readable text. This function is not parameterized but requires an argument to operate. It takes an object regardless of its datatype, converts it into a string and returns the result in its place. When used on a null reference, this method returns a null value.

The following example demonstrates the string representation of a List object, a Set Object and a Map Object. We accomplish this by using the toString() method on said objects.

			

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class tostring {

    public static void main(String args[]) {

        List <String> nameList = new ArrayList<>();
        nameList.add("John");
        nameList.add("Derek");
        nameList.add("Molly");
        System.out.println(nameList.toString());

        Set <String> subjectListSet = new HashSet<>();
        subjectListSet.add("Java");
        subjectListSet.add("Python");
        subjectListSet.add("Java");
        subjectListSet.add("Ada");
        System.out.println(subjectListSet.toString());

        Map<String, String> codeListMap = new HashMap<>();
        codeListMap.put("1021", "Justin");
        codeListMap.put("1056", "Samantha");
        codeListMap.put("1234", "Norman");
        codeListMap.put("2367", "Dimitri");
        System.out.println(codeListMap.toString());

        Map<Integer, String[]> employeeListMap = new HashMap<>();
        employeeListMap.put(1021, new String[]{"Justin","Senior Manager","Sales"});
        employeeListMap.put(1056, new String[]{"Samantha","Supervisor","Production"});
        employeeListMap.put(1234, new String[]{"Norman","Officer","Accounts"});
        employeeListMap.put(2367, new String[]{"Dimitri","Manager","Systems"});
        System.out.println(employeeListMap.toString());
    }
}

				

Output:

[John, Derek, Molly][Java, Python, Ada] {1234=Norman, 2367=Dimitri, 1056=Samantha, 1021=Justin} {1056=[Ljava.lang.String;@5a07e868, 1234=[Ljava.lang.String;@76ed5528, 1021=[Ljava.lang.String;@2c7b84de, 2367=[Ljava.lang.String;@3fee733d}

On careful observation, you may note that the output of employeeListMap shows a Hexadecimal value, which is not human-readable.

The toString() method is a member of the Java Object class. The Java Object class supplies the implementation of this method by default. All java classes inherit the Object class, which allows them to override the method if needed. The default implementation returns a string containing the class name and hashcode of the given object separated by a '@', as seen in the employeeListMap example above.

			

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

				

We shall now create a class, observe what we get from its default implementation and then override the method to get a more representative output.

			

public class Employee {

    int empno;
    String empname;
    String desig;
    String dept;

    Employee (int empno, String empname, String desig, String dept) {
        this.empno = empno;
        this.empname = empname;
        this.desig = desig;
        this.dept = dept;
    }

    public static void main(String args[]) {

        Employee e = new Employee(1021,"Justin","Senior Manager","Sales");
        System.out.println(e); // toString() is called implicitly

    }
}

				

Output:

//Output – Class name @ Hashcode Employee@5a07e868

The default implementation outputs the class name and the object's Hashcode, separated by @. Let us see how we override this.


Overriding the default implementation

As mentioned earlier, all java classes can override the toString() methods, as demonstrated by the following code.

			

public class Employee {

    int empno;
    String empname;
    String desig;
    String dept;

    Employee (int empno, String empname, String desig, String dept) {
        this.empno = empno;
        this.empname = empname;
        this.desig = desig;
        this.dept = dept;
    }

    // Display all the fields of the object
    @Override
    public String toString() {
        return "[Empno: " + empno + " Name: " + empname + " Desig: " + desig + " Dept: " + dept + "]";
    }
    public static void main(String args[]) {
        Employee e = new Employee(1021,"Justin","Senior Manager","Sales");
        System.out.println(e.toString());
    }
}

				

Output:

[Empno: 1021 Name: Justin Desig: Senior Manager Dept: Sales]