Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString() function

 
Ravissant Markenday
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi everyone !

Could anyone please tell me the true utility of the toString() and the valueOf() methods?I know the toString() is defined in the java.lang package and hence is automatically available to all classes.
What i want to know is how and where are the two functions basically used IMPLICITLY, for ex. the System.out.println("xyz") and the concatenation(+) operations and how exactly they work.

thanks in advance,

warm regards,
Ravissant Markenday
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually toString() resides in the Object class and thus is accessible to all other classes that extend Object. toString() is an object's way of saying this is my human readable string format (in most cases). You can override the toString() function to give your object a meaningful representation when you try to print it to a console or elsewhere.

System.out.println() uses the toString() representation of the objects that you pass to it.

valueOf() just returns a String representaion of whatever you pass as an argument (in the String class). Look at the APIs to find out the range of overloaded arguments.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The utility of the valueOf() methods in the String (and Integer and Double) class is that they are creational methods which abstracts away object creation. In other words, the object may be internally constructed using the *new* keyword, or it may be returned from a cache, or it may even return a subclass of the object (not likely in String or the Number classes, but possible). There is a lengthy recent discussion about creational methods and how they relate to other *factory* type patterns here.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic