运算符
一、算数运算
1、使用%运算符
-
取余(取模),取余数,可用于整数、char、浮点数
//1.算数运算 % // !当 % 前面数字比后面小时,余数为其本身。 int i1 = 5 % 2; int i2 = 2 % 5; System.out.println(i1);//1 System.out.println(i2);//2
2、自增自减运算符(++、–)
-
前置自增自减,先自增在使用;后置自增自减,先使用在自增自减
//2、自增自减运算 //注:前置自增自减,先自增在使用;后置自增自减,先使用在自增自减 //前置++||--a int a = 1; int b = ++a; System.out.println(a);//2 System.out.println(b);//2 //后置 int a1 = 1; int b1 = a1++; System.out.println(a1);//2 System.out.println(b1);//1
二、关系运算
-
<、>、<=、>=、==、!=
boolean a = 1 < 2;//true boolean b = 1 > 2;//false boolean c = 1 == 2;//true boolean d = 1 != 2;//false
三、逻辑运算
-
逻辑运算符 非(!),与(&&),或(||)
boolean s1 = !(true);//flase 取反 boolean s2 = 1>2 || 1<2;//true || 全部为flase才为flase,一个为true结果为true; boolean s3 = 1>2 && 1<2;//flase && 全部为true才为true,一个为flase结果为flase; System.out.println(s1); System.out.println(s2); System.out.println(s3);
-
短路运算
int i1 = 2; int i2 = 2; boolean b1 = 1 < 2 || 2 > ++i1;//i1=2 因为 || 有一个为true结果就为true了 所以后面的值就不进行了运算了,直接短路了 boolean b2 = 1 > 2 && 2 < ++i2;//i2=2 因为 && 有一个为flase结果就为flase System.out.println(b1);//true System.out.println(i1);//2 System.out.println(b2);//flase System.out.println(i2);//2
总:&& 一假必假, || 一真必真
四、赋值运算
// 赋值运算连接使用
int x,y,z;
x = y = z = 100;//x = (y = (z = 100)) 是把后面表达式的值赋值给前面的变量
//复合赋值
x += 100; // <==> x = x + 100;
五、字符串连接符
String s1 = "该同学的成绩为:";
String s2 = s1 + 100;//+为拼接
System.out.println(s2);//该同学的成绩为:100
-
“+” 什么时候为加,什么时候为字符串连接
String sec = " "; System.out.println(100 + sec + 200); //100 200 System.out.println(100 + 200 + sec); //300 System.out.println(sec + 100 + 200); // 100200 System.out.println(100 + 200 + sec + 300 +400); // 300 300400
结论:+ 左右两边都是数值为加,只要有一边为字符串为连接
六、三目运算符(重点源码)
//判断式 ? 表达式1 : 表达式2 判断为true执行表达式1,flase执行表达式2
String sc1 = 95 > 80 ? "优秀" : "不符合优秀";
String sc2 = 70 > 80 ? "优秀" : "不符合优秀";
System.out.println(sc1);//优秀
System.out.println(sc2);//不符合优秀
-
三目运算符的嵌套使用
//三目运算符的嵌套使用 ,判断2000年是不是闰年 int year = 2000; String ya = (year % 4 == 0 && year / 100 != 0) ? "闰年" : (year % 400 == 0 ? "闰年" : "平年"); System.out.println(ya);//闰年