• Index

#### 布尔运算

Last updated: ... / Reads: 9353922 Edit

• 比较运算符：`>``>=``<``<=``==``!=`
• 与运算 `&&`
• 或运算 `||`
• 非运算 `!`

``````boolean isGreater = 5 > 3; // true
int age = 12;
boolean isZero = age == 0; // false
boolean isNonZero = !isZero; // true
boolean isAdult = age >= 18; // false
boolean isTeenager = age >6 && age <18; // true
``````

• `!`
• `>``>=``<``<=`
• `==``!=`
• `&&`
• `||`

### 短路运算

``````// 短路运算
----
public class Main {
public static void main(String[] args) {
boolean b = 5 < 3;
boolean result = b && (5 / 0 > 0);
System.out.println(result);
}
}
``````

``````boolean result = true || (5 / 0 > 0); // true
``````

### 三元运算符

Java还提供一个三元运算符`b ? x : y`，它根据第一个布尔表达式的结果，分别返回后续两个表达式之一的计算结果。示例：

``````// 三元运算
----
public class Main {
public static void main(String[] args) {
int n = -100;
int x = n >= 0 ? n : -n;
System.out.println(x);
}
}
``````

### 练习

``````// 布尔运算
public class Main {
public static void main(String[] args) {
----
int age = 7;
// primary student的定义: 6~12岁
boolean isPrimaryStudent = ???;
System.out.println(isPrimaryStudent ? "Yes" : "No");
----
}
}
``````