Difference between toString and String.valueOf in Java.

This has been a very confusing part for anyone who is new to Java. Learning string methods are always cumbersome and there are lots of it. But if you find 2 methods that look like to do the same work, this can confuse anyone. So this post will tell you the difference between Java’s toString() and String.valueOf() method.

Java toString()

Java’s toString() method is used for the string representation of an object. Whenever we print something that is in the form of a string, Java internally overrides toString method which is defined in the object class.

Whenever we write: System.out.print(“10”) or something like that, Java internally overrides toString() method and print 10 as in the form of String.

Java String.valueOf()

Java’s String.valueOf() is an overloaded method which is used to convert other types of object into String. It can convert boolean, char, float, long, double, to String. Whenever we call this method, Java internally analyses the passed argument and select the appropriate overloaded function.

Now here comes the main differences between these two functions.

Probably you will be seeing that these two functions are doing the same work every time, but there is some catch (Java can never be so straight).

  1. If we pass a null argument to String.valueOf() method than method will return null as output, but passing the null instance to toString() method will raise a NullPointerException making it less safe for doing work in which any data can come.
  2. Also toString() is used for objects whereas String.valueOf() is used for primitives.
  3. Only the String.valueOf() method is used to get the String representation of its parameter object. The toString method (which all classes have) does not take a parameter.  

So this is the difference between String.valueOf() and toString() method. Do share the knowledge.

  • Add Your Comment