Best approach to converting Boolean object to string in java(在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);
以上哪一项会更有效?
推荐答案
我认为它们之间不会有任何显着的性能差异,但我更喜欢第一种方式.
I don't think there would be any significant performance difference between them, but I would prefer the 1st way.
如果你有一个 Boolean 引用,如果你的引用是 null,Boolean.toString(boolean) 将抛出 NullPointerException代码>.因为引用在传递给方法之前被拆箱为 boolean.
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() 方法如源代码所示,显式 null 检查:
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();
}
只需测试这段代码:
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中将布尔对象转换为字符串的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在java中将布尔对象转换为字符串的最佳方法
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
