从Java8开始Boolean类型多了3个方法:logicalAnd、logicalOr和logicalXor,这是为了支持函数式编程添加的方法,作用其实和我们手动判断两个变量true或false是相似的。
例如:
a && b,换成Boolean类型提供的方法就是:Boolean.logicalAnd(a,b)
a || b,换成Boolean类型提供的方法就是:Boolean.logicalOr(a,b)
看源码:
public static boolean logicalAnd(boolean a, boolean b) {
return a && b;
}
public static boolean logicalOr(boolean a, boolean b) {
return a || b;
}
public static boolean logicalXor(boolean a, boolean b) {
return a ^ b;
}
看demo:
/**
* logicalAnd、logicalOr和logicalXor
*/
public class BooleanTest {
public static void main(String[] args) {
Boolean a = new Boolean(true);
Boolean b = new Boolean(false);
Boolean c = new Boolean(true);
boolean d = true;
boolean e = false;
System.out.println(Boolean.logicalAnd(a,b));
System.out.println(Boolean.logicalAnd(a,c));
/*
false
true
*/
System.out.println(Boolean.logicalOr(a,b));
System.out.println(Boolean.logicalOr(a,c));
/*
true
true
*/
System.out.println(Boolean.logicalOr(a,d));
System.out.println(Boolean.logicalOr(a,e));
System.out.println(Boolean.logicalOr(b,e));
/*
true
true
false
*/
System.out.println(Boolean.logicalXor(a,d));
System.out.println(Boolean.logicalXor(a,e));
System.out.println(Boolean.logicalXor(b,e));
/*
false
true
false
*/
}
}