Best approach to converting Boolean object to string in java

后端 未结 7 865
暖寄归人
暖寄归人 2020-12-13 01:51

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

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

or

Boolean b = true;
Str         


        
7条回答
  •  抹茶落季
    2020-12-13 02:32

    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.

提交回复
热议问题