Thursday, December 5, 2019

Different Methods to convert object into String

  1. String.valueOf() 
  2. Object.toString()
  3. Integer.toString(int i)
  4.  new String()

String.valueOf() vs. Object.toString(): 

  • Primitive types don't have a "toString".. so String.valueOf is used. 
  • if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
public static void main(String args[]) {  
    String str = null;
    System.out.println(String.valueOf(str));  // This will print a String equal to "null"        
    System.out.println(str.toString()); // This will throw a NullPointerException
} 


Integer.toString(int i) vs String.valueOf(int i)

One huge difference is that if you invoke toString() in a null object you'll get a NullPointerException whereas, using String.valueOf() you may not check for null.



In String type we have several method valueOf
static String   valueOf(boolean b) 
static String   valueOf(char c) 
static String   valueOf(char[] data) 
static String   valueOf(char[] data, int offset, int count) 
static String   valueOf(double d) 
static String   valueOf(float f) 
static String   valueOf(int i) 
static String   valueOf(long l) 
static String   valueOf(Object obj) 
So for integers we have
Integer.toString(int i)
for double
Double.toString(double d)

 new String()  : 
create new instance of string 



No comments:

Post a Comment