Java支持的运算符如下:
算数运算符:+、-、*、/、%、++、--
赋值运算符:=
关系运算符:>、<、>=、<=、==、!=、instanceof
逻辑运算符:&&、||、!
位运算符:&、|、^、~、>>、<<、>>>
条件运算符: ? :
扩展赋值运算符:+=、-=、*=、/*
1、如果类型转换的优先级最高为Long类型,则转换为Long类型;Long以下的类型都转为int(不管数据中存不存在int类型),如果有比Long类型更高优先级的则向更高的转 。简而言之,如果所计算数据的类型只包含int、short、byte中的任意一种,则都转换为int类型。
public class Demo {
public static void main(String[] args) {
Long a = 1213_1231_2321_2112_11L;
int b = 171;
short c = 22221;
byte d = 127;
System.out.println(a+b+c+d);//输出类型为Long
System.out.println(b+c+d);//输出类型为int
System.out.println(c+d);//输出类型为int
//如果类型转换的优先级最高为Long类型,则转换为Long类型;Long以下的类型都转为int(不管数据中存不存在int类型),如果有比Long类型更高优先级的则向更高的转
//简而言之,如果所计算数据的类型只包含int、short、byte中的任意一种,则都转换为int
}
}
2、模运算
public class Demo {
public static void main(String[] args) {
//模运算,取余
int a = 27;
int b = 2;
System.out.println(a%b);//输出结果为7
}
}
3、自增运算符。a++:先用后加,++a:先加后用。自减运算符原理相同
public class Demo {
public static void main(String[] args) {
int a = 3;
int b = a++;
int c = ++a;
System.out.println(a);//输出结果 5
System.out.println(b);//输出结果 3
System.out.println(c);//输出结果 5
}
}
4、幂运算
//计算2^3
Math.pow(2,3);//输出结果 8
5、逻辑运算
&& :逻辑与运算 都为真,则结果为真
|| :逻辑或预算 有一个为真,则结果为真
!:逻辑非运算 取相反结果,如果为真则结果为假,如果为假则结果为真
//逻辑运算
boolean a = true;
boolean b = false;
System.out.println(a && b);//逻辑与运算 都为真,则结果为真。输出结果为false
System.out.println(a || b);//逻辑或预算 有一个为真,则结果为真。输出结果为true
System.out.println(! a);//逻辑非运算 取相反结果,如果为真则结果为假,如果为假则结果为真 输出结果为false
短路运算:如果&&运算符前面的执行结果为false,则不执行&&运算符后面的计算
int c = 5;
boolean d = (c > 6) && (c++ < 4);
System.out.println(c);//输出结果为 5
System.out.println(c);//输出结果为 5
6、位运算
A = 0011 1100
B = 0000 1101
与运算:A&B = 0000 1100
或运算:A|B = 0011 1101
非运算:~B = 1111 0010
异或:A^B = 1100 0011
左移:<< 左移一位相当于 *2
右移:>> 右移一位相当于 /2
用位运算计算2*8
0000 0000 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16
2*8利用位运算进行计算是将2左移3位,即2<<3 ,结果为8
7、扩展赋值运算符
int a = 10;
int b = 20;
a += b;//等同于 a = a + b
System.out.println(a);//输出结果为 30
//拓展:字符串连接符+
System.out.println(a + b + "");//30
System.out.println("" + a + b);//1020
8、三元运算符
a ? b : c 如果a==true 则输出结果为b,否则输出结果为c
//三元运算符 a ? b : c
int score = 90;
String result = score > 60 ? "及格" : "不及格";
System.out.println(result);