Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object of class having toString() method

 
Jyoti Vaskar
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If an object of a class having toString() method, is printed, It prints String value returned by method??
How this happen??

Is object value is string, returned by tostring() method in the class??

can anybody please explain?
 
Nitish Bangera
Ranch Hand
Posts: 537
Eclipse IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What wrong in that now??? You are overriding the toString method of the method in your class and then calling your method toString??? What was the problem here??
 
Jyoti Vaskar
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nitish Bangera wrote:What wrong in that now??? You are overriding the toString method of the method in your class and then calling your method toString??? What was the problem here??


Yes I override the method in my class.

But I am confused for this below,
when I try to print the value of the object of class A i.e. System.out.println(a);(A a=new A())
this prints string "This is A tostring" which is returned by toSting() method.

Now is it the object value??
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The toString() function is a way of -well- turning your Object into a string somehow. This can either be an explanation or whatever you feel makes sense.

The default implementation by the Object class throws back the instances' reference code.
 
Rusty Shackleford
Ranch Hand
Posts: 490
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println(a) and System.out.println(a.toString()) are equivalent. They both call toString which returns a string, which println prints. All objects in Java have a toString method because it is part of Object.

 
Deepak Borania
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By overriding the toString(), you define what should be returned when you want to use you object as a string. This string can be anything you want. It may just return value of fields as a string, or anything else..

 
Maneesh Godbole
Saloon Keeper
Posts: 11070
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the PrintStream source code:



and from the String source code
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic