05. 逻辑运算符

Author Avatar
FengXueke 10月 18, 2022

post05

逻辑运算符

逻辑运算符 AND(&&)、OR(||)以及 NOT(!)能生成一个布尔值(true 或 false)——以自变量的逻辑关 系为基础.

  • 用法示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.isflee.c03_1_6_bool;

import java.util.Random;

//: Bool.java
// Relational and logical operators import java.util.*;
public class Bool {
//使用关系和逻辑运算符
public static void main(String[] args) {
Random rand = new Random();
int i = rand.nextInt() % 100;
int j = rand.nextInt() % 100;
prt("i = " + i);
prt("j = " + j);
//在预计为String 值的地方使用,布尔值会自动转换成适当的文本形式。
prt("i > j is " + (i > j));
prt("i < j is " + (i < j));
prt("i >= j is " + (i >= j));
prt("i <= j is " + (i <= j));
prt("i == j is " + (i == j));
prt("i != j is " + (i != j));
// Treating an int as a boolean is
// not legal Java
//! prt("i && j is " + (i && j));
//! prt("i || j is " + (i || j));
//! prt("!i is " + !i);
prt("(i < 10) && (j < 10) is " + ((i < 10) && (j < 10)) );
prt("(i < 10) || (j < 10) is " + ((i < 10) || (j < 10)) );
}
static void prt(String s) {
System.out.println(s);
}

} ///:~

  • 关于短路

操作逻辑运算符时,我们会遇到一种名为“短路”的情况。这意味着只有明确得出整个表达式真或假的结 论,才会对表达式进行逻辑求值。因此,一个逻辑表达式的所有部分都有可能不进行求值

  • 短路示例, 详细请看注释
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.isflee.c03_1_6_short_circuit;

//: ShortCircuit.java
// Demonstrates short-circuiting behavior // with logical operators.
public class ShortCircuit {
static boolean test1(int val) {
System.out.println("test1(" + val + ")");
System.out.println("result: "+ (val < 1));
return val < 1;
}
static boolean test2(int val) {
System.out.println("test2(" + val + ")");
System.out.println("result: " + (val < 2));
return val < 2;
}
static boolean test3(int val) {
System.out.println("test3(" + val + ")");
System.out.println("result: " + (val < 3));
return val < 3;
}
public static void main(String[] args) {
//假设手动算出来:true && false && true
//实际程序运行: true && false
//短路:只有明确得出整个表达式真或假的结论,才会对表达式进行逻辑求值。因此,一个逻辑表达式的所有部分都有可能不进行求值
if(test1(0) && test2(2) && test3(2))
System.out.println("expression is true");
else
System.out.println("expression is false");
}
} ///:~

运行结果:

test1(0)

result: true

test2(2)

result: false

expression is false