Java 逻辑运算符
执行结果截图

代码:
public class LogicalOperator {
public static void main(String[] args) {
// 与(and) 或(or) 非(取反)
boolean a = true;
boolean b = false;
System.out.println("a && b:" + (a && b));
System.out.println("a || b:" + (a || b));
System.out.println("!(a && b):" + !(a && b));
// 以下会测试短路运算:双与、双或运算符有可能导致++运算符用不上从而不执行自增
int c = 5;
System.out.println("Initialize c value, c:" + c);
// c<4的结果是false,那么用c<4去&&任何值都是false
boolean f = (c < 4) && (c++ > 4);
System.out.println("After run (c < 4) && (c++ > 4),now c:" + c);
// c++是先用再执行c=c+1,用不上就不执行c=c+1。这里c<4的结果值是false,false会短路其后的&&(双与)运算(不执行与运算),
// 从而(c++>4)这段代码也被直接跳过,c++不执行
System.out.println("After run (c < 4) && (c++ > 4),result of value:" + f);
c = 5;
System.out.println("Initialize c value, c:" + c);
// c>4的结果是true,那么用c>4去||任何值都是true
boolean g = (c > 4) || (c++ > 4);
System.out.println("After run (c > 4) || (c++ > 4),now c:" + c);
// c++是先用再执行c=c+1,用不上就不执行c=c+1。这里c>4的结果值是true,true会短路其后的||(双或)运算(不执行或运算),
// 从而(c++>4)这段代码也被直接跳过,c++不执行
System.out.println("After run (c > 4) || (c++ > 4),result of value:" + g);
c = 3;
System.out.println("Initialize c value, c:" + c);
boolean h = (c < 4) && (c++ == 3);
System.out.println("After run (c < 4) && (c++ == 3),now c:" + c);
// c++是先用再执行c=c+1,用不上就不执行c=c+1。这里c<4的结果值是true,true不能短路其后的&&(双与)与运算(必须执行与运算),
// 从而(c++==3)这段代码未被跳过(会先执行c==3再执行c=c+1)
System.out.println("After run (c < 4) && (c++ == 3),result of value:" + h);
c = 4;
System.out.println("Initialize c value, c:" + c);
boolean k = (c > 4) || (++c == 4);
System.out.println("After run (c > 4) || (++c == 4),now c:" + c);
// ++c是先执行c=c+1再用,用不上就不执行c=1。这里c<4的结果值是false,false不能短路其后的||(双或)运算(必须执行或运算),
// 从而(++c==4)这段代码未被跳过(会先执行执行c=c+1再执行c==4)
System.out.println("After run (c > 4) || (++c == 4),result of value:" + k);
}
}

浙公网安备 33010602011771号