hello,大家好,这里是可傥。今天我们来说一下基本数据类型boolean和其包装类Boolean。
今天我们结合以下例子来说明这两者的区别。
public class BooleanTest {
private Boolean isTrue;
/**
* Getter method for property<tt>isTrue</tt>.
*
* @return property value of isTrue
*/
public Boolean getTrue() {
return isTrue;
}
/**
* Setter method for property <tt>isTrue</tt>.
*
* @param isTrue value to be assigned to property isTrue
*/
public void
setTrue(Boolean isTrue) {
this.isTrue = isTrue;
}
public static void main(String[] args) {
//boolean a = null;
Boolean a = null;
Boolean b = new Boolean(null);
Boolean c = new Boolean("true");
if (null ==a){
a =true;
}
System.out.println(a);
System.out.println(b);
BooleanTest booleanTest = new BooleanTest();
booleanTest.setTrue(null);
System.out.println(booleanTest.isTrue);
System.out.println(booleanTest.getTrue());
}
}
一、是否可以为null
Boolean因为是一个类,所以他的引用对象可以为null;
Boolean a= null或者Boolean b = new Boolean(null)都是允许的,而基本数据类型boolean只能为true or false。
二、Boolean 可以 new 中引入字符串
要知道Boolean为什么可以new中加入字符串,我们就打开Boolean的源码,源码是这样的:
/**
* Allocates a {@code Boolean} object representing the value
* {@code true} if the string argument is not {@code null}
* and is equal, ignoring case, to the string {@code "true"}.
* Otherwise, allocate a {@code Boolean} object representing the
* value {@code false}. Examples:<p>
* {@code new Boolean("True")} produces a {@code Boolean} object
* that represents {@code true}.<br>
* {@code new Boolean("yes")} produces a {@code Boolean} object
* that represents {@code false}.
*
* @param s the string to be converted to a {@code Boolean}.
*/
public Boolean(String s) {
this(parseBoolean(s));
}
/**
* Parses the string argument as a boolean. The {@code boolean}
* returned represents the value {@code true} if the string argument
* is not {@code null} and is equal, ignoring case, to the string
* {@code "true"}. <p>
* Example: {@code Boolean.parseBoolean("True")} returns {@code true}.<br>
* Example: {@code Boolean.parseBoolean("yes")} returns {@code false}.
*
* @param s the {@code String} containing the boolean
* representation to be parsed
* @return the boolean represented by the string argument
* @since 1.5
*/
public static boolean parseBoolean(String s) {
return ((s != null) && s.equalsIgnoreCase("true"));
}
这边就可以很明显的看到,字符串唯有"true"且不为null的时候才是true(true不区分大小写),其他全部为false。
三、阿里巴巴Java开发手册
*关于基本数据类型与包装数据类型的使用标准如下:
1) 【强制】所有的 POJO 类属性必须使用包装数据类型。
2) 【强制】RPC 方法的返回值和参数必须使用包装数据类型。
3) 【推荐】所有的局部变量使用基本数据类型。
说明:POJO 类属性没有初值是提醒使用者在需要使用时,必须自己显式地进行赋值,任何 NPE 问题,或
者入库检查,都由使用者来保证。
正例:数据库的查询结果可能是 null,因为自动拆箱,用基本数据类型接收有 NPE 风险。
反例:某业务的交易报表上显示成交总额涨跌情况,即正负 x%,x 为基本数据类型,调用的 RPC 服务,调
用不成功时,返回的是默认值,页面显示为 0%,这是不合理的,应该显示成中划线-。所以包装数据类型
的 null 值,能够表示额外的信息,如:远程调用失败,异常退出。*
以上是手册的原话,所以一般来说,最好用包装类来接收数据库的数据,防止NPE问题。
这就是之前代码上的用Boolean包装类来定义而不是用基本数据类型来定义,就是这个原因。
Boolean和boolean的区别就讲到这,这里是可傥,将会分享自己的所学以及所得,欢迎大家一起交流。csdn地址为:https://blog.csdn.net/kaneand...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。