1.1算术运算符
取余%的计算结果的正负由被除数决定
class Demo3 { public static void main(String[] args) { System.out.print(5%-2); } }自增运算符
class Demo3 { public static void main(String[] args) { int m = 6,n; n = m++; System.out.println("m:" + m + "\t" + "n:" + n); } } class Demo3 { public static void main(String[] args) { int m = 6,n; n = ++m; System.out.println("m:" + m + "\t" + "n:" + n); } } class Demo3 { public static void main(String[] args) { int m , n=5; m=++n + n++ + ++n; System.out.println("m:" + m + "\t" + "n:" + n); } } class Demo3 { public static void main(String[] args) { int m, n = 6; m = n-- + --n; System.out.println("m:" + m + "\t" + "n:" + n); } }1.2复合赋值运算符
+= -= *= /= %=
class Demo3 { public static void main(String[] args) { short s = 5; s = s+5; System.out.print(s); } } class Demo3 { public static void main(String[] args) { short s = 5; s += 5; System.out.print(s); } }结论:利用复合赋值运算符编译不会出错,内部做了强制类型转换
1.3关系运算符
>= < <= == !=运算符是有值的,由运算符和数据组合在一起的式子就是表达式
class Demo3 { public static void main(String[] args) { int a = 5, b = 6, c=8; System.out.println(a<b); System.out.println(a>b); System.out.println(c==88); System.out.println(c!=88); } }总结:关系表达式的值只有True和False两种情况 1.4逻辑运算符
&&(短路与) ||(短路或) !(非) &(逻辑与) |(逻辑或)
&&:短路与,如果左边的表达式为false,那么不会计算右边的表达式 &:逻辑与,如果左边的表达式为false,还会计算右边的表达式 ||:短路或,如果左边的表达式为true,那么不会计算右边的表达式 |:逻辑或,如果左边的表达式为true,还会计算右边的表达式
1.5位运算符
&(与) |(或) ^(异或) ~(取反) <<(左移) >>(无符号右移)
&(与): |(或): ^(异或): 注意:连续异或两次又得到结果7 ~(取反):
class Demo4 { public static void main(String[] args) { System.out.println(~8); } }得到结果为-9
<<(左移):
class Demo4 { public static void main(String[] args) { System.out.println(6<<2); } }得到结果为24
>>(右移)
得到结果我-2
>>>(无符号右移)
用于进制转换,例如将十进制的60转换为16进制的数字 十进制转换为十六进制
class Demo4 { public static void main(String[] args) { int num = 60; int n1 = num&15; //将数字与二进制1111相与,得到低4位 int n2 = num>>>4; System.out.println(n2 + "" +(char)(n1-10+'a')); } }1.6三元运算符 1.7习题总结
class Demo5 { public static void main(String[] args) { //最有效的方式计算2*8 System.out.println(2<<3); //对两个整数变量进行交换 int a=5, b=6; a=a^b; b=a^b; a=a^b; System.out.println("a=" + a +'\t' + "b=" + b); //利用三元运算符计算最大值max int x=6, y=9, z=78; int num = x<y?y:x; int max = num<z?z:x; System.out.println(max); } }1.8运算符的优先级 一元运算符–>算术运算符、位运算符–>关系运算符–>逻辑运算符–>得到计算结果
(1)先执行循环体, 再判断循环条件是否成立; (2)如果循环条件成立, 继续执行循环体; (3)如果循环条件不成立, 结束循环。 while循环和do-while循环的区别 :while循环可能一次都不会执行,而do-while循环至少执行一次。
for循环