在java中将Boolean对象转换为字符串的最佳方法

时间:2022-09-15 20:30:41

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?

以上哪一项会更有效率?

6 个解决方案

#1


125  

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.

如果您有一个布尔引用,那么如果您的引用为null,则Boolean.toString(boolean)将抛出NullPointerException。由于引用在传递给方法之前未被装箱为布尔值。

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

同时,String.valueOf()方法作为源代码显示,进行显式null检查:

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.

对于原始布尔值,没有区别。

#2


23  

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

如果您确定您的值不为null,则可以使用第三个选项

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

如果您想要为null安全,请使用String.valueOf(b)代码

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.

所以当你看到它将首先测试null并稍后在你的对象上调用toString()方法。


Calling Boolean.toString(b) will invoke

调用Boolean.toString(b)将调用

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.

这比b.toString()慢一点,因为JVM需要首先将unbox布尔到布尔值,它将作为参数传递给Boolean.toString(...),而b.toString()在布尔对象中重用私有布尔值字段保持其状态。

#3


3  

public class Sandbox {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Boolean b = true;
        boolean z = false;
        echo (b);
        echo (z);
        echo ("Value of b= " + b +"\nValue of z= " + z);
    }

    public static void echo(Object obj){
        System.out.println(obj);
    } 

}
Result
--------------
true
false
Value of b= true
Value of z= false
--------------

#4


3  

If this is for the purpose of getting a constant "true" value, rather than "True" or "TRUE", you can use this:

如果这是为了获得一个恒定的“true”值,而不是“True”或“TRUE”,你可以使用:

Boolean.TRUE.toString();
Boolean.FALSE.toString();

#5


1  

If you're looking for a quick way to do this, for example debugging, you can simply concatenate an empty string on to the boolean:

如果您正在寻找一种快速的方法来执行此操作,例如调试,您可以简单地将空字符串连接到布尔值:

System.out.println(b+"");

However, I strongly recommend using another method for production usage. This is a simple quick solution which is useful for debugging.

但是,我强烈建议使用其他方法进行生产使用。这是一个简单的快速解决方案,可用于调试。

#6


1  

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

#1


125  

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.

如果您有一个布尔引用,那么如果您的引用为null,则Boolean.toString(boolean)将抛出NullPointerException。由于引用在传递给方法之前未被装箱为布尔值。

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

同时,String.valueOf()方法作为源代码显示,进行显式null检查:

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.

对于原始布尔值,没有区别。

#2


23  

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

如果您确定您的值不为null,则可以使用第三个选项

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

如果您想要为null安全,请使用String.valueOf(b)代码

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.

所以当你看到它将首先测试null并稍后在你的对象上调用toString()方法。


Calling Boolean.toString(b) will invoke

调用Boolean.toString(b)将调用

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.

这比b.toString()慢一点,因为JVM需要首先将unbox布尔到布尔值,它将作为参数传递给Boolean.toString(...),而b.toString()在布尔对象中重用私有布尔值字段保持其状态。

#3


3  

public class Sandbox {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Boolean b = true;
        boolean z = false;
        echo (b);
        echo (z);
        echo ("Value of b= " + b +"\nValue of z= " + z);
    }

    public static void echo(Object obj){
        System.out.println(obj);
    } 

}
Result
--------------
true
false
Value of b= true
Value of z= false
--------------

#4


3  

If this is for the purpose of getting a constant "true" value, rather than "True" or "TRUE", you can use this:

如果这是为了获得一个恒定的“true”值,而不是“True”或“TRUE”,你可以使用:

Boolean.TRUE.toString();
Boolean.FALSE.toString();

#5


1  

If you're looking for a quick way to do this, for example debugging, you can simply concatenate an empty string on to the boolean:

如果您正在寻找一种快速的方法来执行此操作,例如调试,您可以简单地将空字符串连接到布尔值:

System.out.println(b+"");

However, I strongly recommend using another method for production usage. This is a simple quick solution which is useful for debugging.

但是,我强烈建议使用其他方法进行生产使用。这是一个简单的快速解决方案,可用于调试。

#6


1  

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