Differences between String.valueOf(Object) and Object.toString()

Java String valueOf  method
String class valueOf(Object) method converts different types of values into string.

valueOf() method of String class is static

Using String .valueOf(Object) method, you can convert

  • int to string(public static String valueOf(int i) )
  • long to string(public static String valueOf(lang i) )
  • character to string(public static String valueOf(char c))
  • float to string(public static String valueOf(float f) )
  • double to string(public static String valueOf(double d) )
  • boolean to string(public static String valueOf(boolean b))
  • object to string(public static String valueOf(Object o))
  • char array to string.(public static String valueOf(char[] c)

NOTE :-

  • If string is null then String.valueOf() method will prints null
  • but if string is null then Object.toString() method will throw nullPointerException.

Example:

class Demo {
public static void main(String args[]){  
    String str = null;
    System.out.println(String.valueOf(str));//print null        
    System.out.println(str.toString());//NullPointerException        
} 
}

Leave a comment