运算符
算术运算符: +,-,*,/,%,++,–
int x = 10;
int y = 20;
char z = 'a';
String s = "20";
System.out.println(x+y);//数值+数值=数值 30
System.out.println(x-y);//数值-数值=数值 -10
System.out.println(x+z);//数值+字符=数值 107
System.out.println(x-z);//数值-字符=数值 -87
System.out.println(s+x);//数值+字符串=字符串 2010
字符串连接运算符:+
String s0 = "10";
String s = "20";
System.out.println(s0+s); // 1020
关系(比较)运算符: >,<,>=,<=,==,!=
//比较运算
// ==, != ,> ,< ,<= ,>=
int a = 10;
int b = 20,d=20;
int c = 15;
//==,!= -->数值比较
System.out.println(a==b); //false
System.out.println(a!=b); //true
String s1 = "abc";
String s2 = "def";
//==,!= -->字符串比较
System.out.println(s1==s2); //false
System.out.println(s1!=s2); //true
逻辑运算符: !,& , | , &&,||
“&”和“&&”的区别:
单&时,左边无论真假,右边都进行运算;
双&时,如果左边为真,右边参与运算,如果左边为假,那么右边不参与运算。
“|”和“||”的区别同理,||表示:当左边为真,右边不参与运算。
异或( ^ ):当左右都为true时,结果为false。
理解:异或,追求的是“异”!
// 逻辑运算
// 逻辑与 & --> 全真才真
System.out.println(a<b & b>c); //true & true = true
System.out.println(a>b & b>c); //false & true = false
System.out.println(a>b & b<c); //false & false = false
// 短路与 && --> 全真才真 其中 &&左边表达式为假,则不执行右边表达式
System.out.println(a<b && b>c); //ture && true = true
System.out.println(a>b && b>c); //false && true = false
System.out.println(a>b && ++b>c);//false && true = false
System.out.println(b); //上式&&左边为false,不进行右边算是运算,因此b=20
System.out.println(a>b && b<c); //false && false = false
// 逻辑或 | --> 有真为真
System.out.println(a<b | b>c); //true | true = true
System.out.println(a>b | b>c); //false | true = true
System.out.println(a>b | b<c); //false | false = false
// 短路或 || --> 有真为真 其中 ||左边表达式为真,则不执行右边表达式
System.out.println(a<b || b>c); //true || true = true
System.out.println(a<b || ++d>c); //true || true = true
System.out.println(d);//上式||左边为false,不进行右边算是运算,因此d=20
System.out.println(a>b || b>c); //false || true = true
System.out.println(a>b || b<c); //false || false = false
// 逻辑异或 ^ 相同为false,不同为true
System.out.println(a<b ^ b>c); //true ^ true = false
System.out.println(a>b ^ b>c); //false ^ true = true
System.out.println(a>b ^ b<c); //false ^ false = false
赋值运算符: = ,+ =,- =,* =,/ =
条件运算符
语法:
(条件表达式)? 表达式1:表达式2;
为true,运算后的结果是表达式1;
为false,运算后的结果是表达式2;
表达式1和表达式2为同种类型
条件运算符与if-else的联系与区别:
1)条件运算符可简化if-else语句
2)条件运算符要求必须返回一个结果。
3)if后的代码块可有多个语句
位运算符
// 位运算
//左移 <<
int aa = 2;
System.out.println(aa<<2);
//右移 >>
System.out.println(aa>>2);
//与 & 都为1结果为1
/*
3 0011
4 0100
& 0000 = 0
*/
System.out.println(3 & 4);
//或 | 有1 就是1
/*
3 0011
4 0100
| 0111 = 7
*/
System.out.println(3 | 4);
//异或 ^ 相同为0,不同为1
/*
3 0011
4 0100
^ 0111 = 7
*/
System.out.println(3 ^ 4);
//非 ~ 取反
System.out.println(~3);