Best approach to converting Boolean object to string in java

后端 未结 7 881
暖寄归人
暖寄归人 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:14

    If you are sure that your value is not null you can use third option which is

    String str3 = b.toString();
    

    and its code looks like

    public String toString() {
        return value ? "true" : "false";
    }
    

    If you want to be null-safe use String.valueOf(b) which code looks like

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

    so as you see it will first test for null and later invoke toString() method on your object.


    Calling Boolean.toString(b) will invoke

    public static String toString(boolean b) {
        return b ? "true" : "false";
    }
    

    which is little slower than b.toString() since JVM needs to first unbox Boolean to boolean which will be passed as argument to Boolean.toString(...), while b.toString() reuses private boolean value field in Boolean object which holds its state.

提交回复
热议问题