Best approach to converting Boolean object to string in java

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

    Depends on what you mean by "efficient". Performance-wise both versions are the same as its the same bytecode.

    $ ./javap.exe -c java.lang.String | grep -A 10 "valueOf(boolean)"
      public static java.lang.String valueOf(boolean);
        Code:
           0: iload_0
           1: ifeq          9
           4: ldc           #14                 // String true
           6: goto          11
           9: ldc           #10                 // String false
          11: areturn
    
    
    $ ./javap.exe -c java.lang.Boolean | grep -A 10 "toString(boolean)"
      public static java.lang.String toString(boolean);
        Code:
           0: iload_0
           1: ifeq          9
           4: ldc           #3                  // String true
           6: goto          11
           9: ldc           #2                  // String false
          11: areturn
    

提交回复
热议问题