运算符与表达式
运算符:对常量或变量进行操作的符号
表达式:用运算符把常量或者变量连接起来符合Java语法的式子称之为表达式;不同运算符连接的表达式体现的是不同类型的表达式
如:
c = a + b
- +为运算符
- a + b为表达式,由于 + 是算术运算符,所以
a + b
被称为算术表达式
算术运算符
算术运算
算术运算符 (+、-、*、/、%、++、--)
整数与整数运算只能得到整数,如果要得到浮点数结果,必须有一个小数参与运算
// 算术运算符
System.out.println( 10 / 2);
System.out.println( 10 / 3);
System.out.println( 10 / 2.0);
System.out.println( 10 / 3.0);
整数与字符相加,会将字符转换成ASCII对应的ASCII码,再与整数相加(隐式转换、自动提升)
// 整数与字符相加
System.out.println( 1 + 'a'); // 98
需要记忆的ASCII码
'a'
- 97'A'
- 65'0'
- 48
字符串与任意类型数据相加,会将内容拼接在一起
// 字符串与任意类型相加
System.out.println( "Hello " + 666); // Hello 666
System.out.println( "Hello " + true); // Hello true
自增、自减
i-- (先自减1,后运算)
--i (先运算,后自减)
自增、自减不改变变量本身的类型
int i1 = 10;
int i2 = 20;
int i = i1++;//先赋值,再+1
System.out.println("i = " + i);//i = 10
System.out.println("i1 = " + i1);//i1 = 11
i = ++i1;//先+1再赋值
System.out.println("i = " + i);//i = 12
System.out.println("i1 = " + i1);//i1 = 12
i = i2--;//先赋值再-1
System.out.println("i = " + i);//i = 20
System.out.println("i2 = " + i2);//i1 = 19
i = --i2;
System.out.println("i = " + i);//i = 18
System.out.println("i2 = " + i2);//i1 = 10
赋值运算符
支持连续赋值
拓展赋值运算符(+=、-=、%=、/=、*=)
有的时候会自带强制类型转换
public class 运算符练习一 {
public static void main(String[] args) {
// 练习1
short s = 3;
// s = s + 3 ;//编译错误,short和int结果不能用short接收,要用int
s += 2;//不改变变量本身的类型
// 练习2
// int i = 1;
// i *= 0.1;
// System.out.println(i);//i是整形,结果为1,不为0.1
// i++;
// System.out.println(i);//同理,结果为1
//练习3
int m = 2;
int n = 3;
n *= m++;
System.out.println("m=" + m);//3
System.out.println("n=" + n);//先+1,再和n相乘,结果为6
// 练习4
int n = 10;
n += (n++) + (++n);//n=n+(n++) + (++n)
System.out.println(n);//32
}
}
关系运算符(比较运算符)
instanceof 检查是否是类的对象
比较运算符的结果都是boolean类型
逻辑运算符
&逻辑与
|逻辑或
!逻辑非
^逻辑异或(一样为false,不一样为true)
短路逻辑运算符:
&&短路与(前面为假,后面语句不执行)
||短路或 (前面为真,后面语句不执行)
三元运算符
表达式1和表达式2的类型要求一致
public class 三元运算符 {
public static void main(String[] args) {
int m = 12;
int n = 5;
int max = (m>n)? m : n;//条件成立m赋值给max,否则n赋值给max
System.out.println(max);//12
}
}
练习
public class s三元运算符 {
public static void main(String[] args) {
// 练习比较三个数取最大值
int x=12,y=30,z=-43;
int max = ((x>y)? x:y)>z?((x>y)? x:y):z;//嵌套使用
System.out.println(max);//30
}
}
改写成if-else格式
public class s三元运算符 {
public static void main(String[] args) {
int x=12,y=30,z=-43,max;
if (x>y){
max = x;
}else{
max = y;
}
if (max<z){
max = z;
}
System.out.println("三个数的最大值为:" + max);
}
}
优先级和结合性
没啥好说的
位运算符
<<左移(左移动一位相当于*2)
0 0 0 1 0 1 0 1 (21的二进制)(2^4+2²+2^0)
0 0 0 1 0 1 0 1 0 0 (向左移出两位,后面用0补齐,得到新的数字)
对应: 64 + 16 + 4 =2^6+2^4+2²=2²(2^4+2²+2^0)=21 * 2²
public class 位运算 {
public static void main(String[] args) {
int i = 21;
System.out.println("i<<2=" + (i << 2));//84
}
}
右移(右移一位相当于/2)
无符号右移
&与运算
0 0 0 0 1 1 0 0 (12的二进制)
0 0 0 0 0 1 0 1 (5的二进制)
取与 0 0 0 0 0 1 0 0 (4)
|或运算
^异或运算(相同为0,不通过为1)
0 0 0 0 1 1 0 0 (12的二进制)
0 0 0 0 0 1 0 1 (5的二进制)
取异或 0 0 0 0 1 0 0 1 (9的二进制)
~取反运算 (包括符号位在内,全部取反)