javaboolean

Best approach to converting Boolean object to string in java


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?


Solution

  • 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.