toString() method in Java

We can use toString() method to get String representation of an Object.

String s = obj.toString();

Whenever we are trying to print an Object reference, the toString() method will be called internally.

Object o = new Object();
System.Out.Print(o) // => System.Out.Print(o.toString()) 

If Java Class doesn’t contain toString()then Object class toString() will executed.

package Java;

class Car{
    int id;
    String brand;

    public Car(int id, String brand) {
        this.id = id;
        this.brand = brand;
    }


    public static void main(String[] args) {
        Car c = new Car(1,"BMW");
        System.out.println(c);
        System.out.println(c.toString());

    }
}
toString in Java

in the above Java Code Object class toString() get executed, which is implemented as follows –

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

toString() Override

We can override toString() according to our requirment to provode our own String representation.

For Example- Whenever we are trying to print Car object refrence to print Car id and brand, we have to override toString() as given below.

 public String toString() {
        return "Car{" +
                "id=" + id +
                ", brand='" + brand + '\'' +
                '}';
}

In all wrapper classes, Collection classes, String class, StringBuffer and StringBuilder class toString() is overriden for meaningful String representation. Hence it is highly recomended to override toString() in Java classes also.

import java.util.ArrayList;

public class ToStringExample {
    @Override
    public String toString() {
        return "ToStringExample{}";
    }

    public static void main(String[] args) {
        String str = new String("The Code Data");
        System.out.println(str);
        ArrayList arrayList = new ArrayList();
        arrayList.add("The Code");
        System.out.println(arrayList);
        ToStringExample object = new ToStringExample();
        System.out.println(object);

    }
}
toString() Override

Similar Java Tutorials

4 thoughts on “toString() method in Java”

Leave a Comment