秦疆的Java课程笔记:30 基础 三元运算符及小结

发布时间 2023-11-14 14:25:16作者: Acolyte_9527
  • 扩展赋值运算符:+=-=*=/=
public class Dome1 {  
    public static void main(String[] args) {  
        int a = 10;  
        int b = 20;  
        a+=b;//相当于a=a+b  
        System.out.println("a="+(a));  
        int c = 30;  
        int d = 15;  
        c-=d;//相当于c=c-d  
        System.out.println("c="+(c));  
        }  
}
=========
输出:
a=30
c=15
  • *=/=同理,不赘述。秦疆老师不推荐用这些运算符,代码可读性不高。

  • 字符串连接符+:当+两侧出现了String类型,则会把其他数据都转换为String类型,再进行连接。
public class Dome2 {  
    public static void main(String[] args) {  
        int a = 10;  
        int b = 20;  
        System.out.println(a+b);//这里+是运算符  
        System.out.println(""+a+b);//这里+都是连接符,""是一个空的String类型  
        //调换一下输出顺序  
        System.out.println(a+b+"");//前一个+是运算符,后一个+是连接符,按照执行顺序,先运算a+b=30,再连接空字符串,结果还是30  
        }  
}
=========
输出:
30
1020
30

  • 条件运算符:?:(三元运算符)
  • x ? y : z的意义是:如果x==true,则结果为y,否则结果为z
public class Dome3 {  
    public static void main(String[] args) {  
        int score1 = 80;  
        int score2 = 50;  
        String type1 = score1<60 ? "不及格" : "及格";  
        String type2 = score2<60 ? "不及格" : "及格";  
        System.out.println(type1);  
        System.out.println(type2);  
        }  
}
=========
输出:
及格
不及格
  • 这个写法会经常遇到,使得代码精简。另外,后面学流程控制的时候,会学if语句,和这个的作用相似。

  • 算符优先级,最好用()清晰的表示出来。