Boolean和其基本类型boolean的区别
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。