Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ToString method

 
sumaraghavi ragha
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI All

Can any one please tell me what is the use of a toString menthod

With an example

Thanks
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you try to access the value of an Object (reference variable) like this

System.out.println(obj);
OR
String s = "Hello"+obj;

Then the compiler calls the toString() method on that object. So after compilation you code would look like-
System.out.println(obj.toString());
OR
String s = "hello"+obj.toString();

As a developer your job is to provide a toString method with your class and return the relevant details about the object as a String from the toString method.

Eg.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic