Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (6.1k points)
I have started learning Java from the internet. But unable to understand toString method. So kindly help me out with this.

1 Answer

0 votes
by (11.7k points)

In Java, this method comes in handy when a user wants to represent any object as a string. It returns an object as a string.

The compiler of Java automatically invokes the toString() method on the object. Therefore, when the toString method is overridden, we get in return the desired output, which can be the state of an object as well depending on the implementation.

Example:

 class Employee{  

 int id;  

 String name;  

 String city;  

  

 Employee(int id, String name, String city){  

 this.id=id;  

 this.name=name;  

 this.city=city;  

 }  

   

 public String toString()

{

  return id+" "+name+" "+city;  

 }  

 public static void main(String args[])

{  

   Employee e1=new Employee(1001,"Vijay","Banglore");  

   Employee  e2=new Employee(1002,"Deepak","Pune");  

     

   System.out.println(e1);

   System.out.println(e2);

 }  

}  

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 11, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Nov 4, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...