最好的方法在Java Boolean对象转换为字符串 [英] 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);
或
Boolean b = true;
String str = Boolean.toString(b);
其中大于1会更有效?
which one of above would be more efficient?
推荐答案
我不认为会有他们之间的任何显著的性能差异,但我会preFER一号路。
I don't think there would be any significant performance difference between them, but I would prefer the 1st way.
如果你有一个布尔
参考, Boolean.toString(布尔)
将抛出 NullPointerException异常
如果您参考空
。作为基准的拆箱到布尔
传递给方法之前。
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.
在将String.valueOf()
法作为源$ C $ C表示,不明确的空
检查:
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();
}
只是测试这个code:
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.
这篇关于最好的方法在Java Boolean对象转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!