What is the difference between String.valueOf() and toString() in Java?

UPDATED: 01 June 2015
Java String

Each piece of code represents the expertise of developer. You can judge the developer by his/her code. One faulty piece of code may lead to critical damage. So write your code by understanding the fundamental not because someone created and we've to use it.

String.valueOf(argument)
String.valueOf() is null safe. You can avoid java.lang.NullPointerException by using it. It returns "null" String when Object is null. Let explore the source code of String.valueOf().
/* Original Source code */
public static String valueOf(Object obj) {
   return (obj == null) ? "null" : obj.toString();
}

toString()
toString() can cause the java.lang.NullPointerException. It throws java.lang.NullPointerException when Object is null and also terminate the execution of program in case its not handled properly.


Example
public class StringExample {

   public static void main(String[] args) {
      Object obj = "Hello World!";
      System.out.println("String.valueOf(): " + String.valueOf(obj));
      System.out.println("toString(): " + obj.toString());
  
      obj = null;
      System.out.println("String.valueOf(): " + String.valueOf(obj));
      System.out.println("toString(): " + obj.toString());
   }
}

Output
String.valueOf(): Hello World!
toString(): Hello World!
String.valueOf(): null
Exception in thread "main" java.lang.NullPointerException
 at javaQuery.core.StringExample.main(StringExample.java:14)


0 comments :