| 1234567891011121314151617181920212223242526272829 |
- /**
- * @author WanJl
- * @version 1.0
- * @title Demo07
- * @description 三目运算符 三元运算符
- * @create 2026/7/14
- */
- public class Demo07 {
- public static void main(String[] args) {
- /*
- 三目运算符
- 布尔表达式?表达式1:表达式2
- 布尔表达式的结果如果是true,就执行表达式1,否则执行表达式2
- */
- System.out.println(15>8?"hello":"哈哈哈哈");
- System.out.println(15>8?6:"哈哈哈哈");
- int x=10,y=6;
- System.out.println(x>y?"x>y":"x<=y");
- System.out.println(x>y?"x>y":y);
- /*
- 什么时候使用三元运算符,什么时候使用if...else
- 如果是简单的二选一赋值----》三元运算符
- 复杂多个分支逻辑----》if...else
- 嵌套超过2层----》if...else
- 需要执行某段代码而不是返回一个值----》if...else
- */
- }
- }
|