Developers often get into dilemma when they have to convert the object to string representation by choosing between valueOf() and toString() method. Because both the methods do the same thing but in a bit different ways. To give you more context, toString() method is present in Object class and generally overridden in the derived class where as valueOf() is overloaded static methods and present in the String class. The overloaded method can handle primitive types and objects. This method is not standard method as toString(). Some of the classes e.g Integer, Float, Double, etc. also have static implementation. Let’s look at the examples of these methods.

//1st method
public String getString(int num, Boolean boolvar) {
 //Do something with num and boolvar
  return String.valueOf(num) + " " +  String.valueOf(boolvar);
 }

//2nd method
public String getString(int num, Boolean boolvar) {
 //Do somenthing with num and boolvar
 return Integer.toString(num) + Boolean.toString();
 }

In case of String.valueOf() method you don’t have to worry, the overloaded method handles primitive types as well as objects. This method provides an abstraction. If argument type changes you don’t have to change the implementation but this is not the case with toString() method. String.valueOf() has more readability.

If you have an array of Object class containing Float, Integer, Char etc. First you have to identify all the object then type-cast to appropriate class and call toString() method. Which is kind of inefficient. If valueOf() method is called then it matches against the most suitable overloaded method and then toString() is called. This code structure follows good design pattern and looks neat. Here is some implementation example of valueOf() method present in String class.

public static String valueOf(Object obj) {
   return (obj == null) ? "null" : obj.toString();
}
public static String valueOf(int i) {
   return Integer.toString(i);
}

Let’s take another example of these two methods.

Double d = null ;
System.out.println(String.valueOf(d)); //Prints "null"
System.out.println(Double.toString(d)); //Throws NullPointerException 

String.valueOf() prints “null” if the reference is null whereas Dobule.toString() throws NullPointerException. Ideally references should be checked for null before calling toString(). This check can be avoided if you use String.valueOf() method.
Please share your thoughts as comment below.

Hope this blog helped you in some way. If you like this blog then please share it. You can also leave your comment below.

,
Trackback

2 comments untill now

  1. Great post Rakesh. I was searching for the difference between the two. It helped a lot

  2. Devendra @ 2015-08-23 03:33

    Thanks alot. G8 post.
    Keep posting.
    God Bless You.

Add your comment now