by @kodeazy

what is the use of toString() method in java?

Home » java » what is the use of toString() method in java?
  • toString() method provides the string representation of the Object in java
  • It is Inherited from the Object class, which is parent class of all classes in java.

    public String toString(){
        return "name is:"+name+" Age is:"+age+"salary is :"+salary+"\n";
    }
  • Below is an Example of printing an Object without using toString() method in java.

    public class ToStringExample {
    public static void main(String args[]){
        Employee e= new Employee(27,100,"John");
        System.out.println(e);
    
    }
    }
    class Employee{
    int age;
    int salary;
    String name;
    Employee(int age,int salary,String name){
        this.age=age;
        this.salary=salary;
        this.name=name;
    
    }
    }

    Output:

Employee@3fee733d
  • The output I got is hashcode of the object
  • To get the desired string we use toString() method as below

    public class ToStringExample {
    public static void main(String args[]){
        Employee e= new Employee(27,100,"John");
        System.out.println(e);
    
    }
    }
    class Employee{
    int age;
    int salary;
    String name;
    Employee(int age,int salary,String name){
        this.age=age;
        this.salary=salary;
        this.name=name;
    
    }
    public String toString(){
        return "name is:"+name+" Age is:"+age+"salary is :"+salary+"\n";
    }
    }

    Output:

    name is:John Age is:27salary is :100