Best approach to converting Boolean object to string in java

Rachel picture Rachel · Sep 16, 2013 · Viewed 222.5k times · Source

I am trying to convert boolean to string type...

Boolean b = true;
String str = String.valueOf(b);

or

Boolean b = true;
String str = Boolean.toString(b);

which one of above would be more efficient?

Answer

Rohit Jain picture Rohit Jain · Sep 16, 2013

I don't think there would be any significant performance difference between them, but I would prefer the 1st way.

If you have a Boolean reference, Boolean.toString(boolean) will throw NullPointerException if your reference is null. As the reference is unboxed to boolean before being passed to the method.

While, String.valueOf() method as the source code shows, does the explicit null check:

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

Just test this code:

Boolean b = null;

System.out.println(String.valueOf(b));    // Prints null
System.out.println(Boolean.toString(b));  // Throws NPE

For primitive boolean, there is no difference.