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.
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.
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 patternshere.
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter