基本运算符
算数运算符
+ | - | * | / | % | ++ | – |
---|---|---|---|---|---|---|
加 | 减 | 乘 | 除 | 模 | 自增 | 自减 |
除法时,要把类型强转为double
package operator;
public class Demo01 {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println(a+b); //30
System.out.println(a-b); //-10
System.out.println(a*b); //200
//除法要将类型强转为double类型,因为int类型没有小数
System.out.println(a/(double)b); //0.5
}
}
不同类型相加时,自动转换为最高级数据类型,如果都是最小类型,那么都变成int型
package operator;
public class Demo02 {
public static void main(String[] args) {
long a = 123123123L;
int b = 123;
short c = 10;
byte d = 1;
double e = 11.5;
//数中有Long型,所有数都变成Long型,如果都是最小类型,那么都变成int型
System.out.println(a+b+c+d); //123123257
System.out.println(b+c+d); //134
System.out.println(c+d); //11
System.out.println(a+e); //1.231231345E8
}
}
package operator;
public class Demo04 {
public static void main(String[] args) {
int a = 10;
int b = a++; //先输出,再加
int c = ++a; //先加,在输出
System.out.println(a); //12
System.out.println(b); //10
System.out.println(c); //12
}
}
比较运算符
> | < | == | >= | <= | != |
---|---|---|---|---|---|
大于 | 小于 | 等于 | 大于等于 | 小于等于 | 不等于 |
package operator;
public class Demo03 {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 21;
System.out.println(a>b); //false
System.out.println(a<b); //true
System.out.println(a==b);//false
System.out.println(a!=b);//true
System.out.println(c%a); //1
}
}
逻辑运算符
&& | || | ! |
---|---|---|
与 | 或 | 非 |
package operator;
public class Demo05 {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("a && b =" + (a&&b)); //逻辑与 false
System.out.println("a || b =" + (a||b)); //逻辑或 true
System.out.println("!(a && b) =" + !(a&&b)); //逻辑非 true
//短路运算
int c = 5;
boolean d = (c<4)&&(c++>4);
System.out.println(c); //5
System.out.println(d); //false
}
}
短路运算说明 运算如果第一个条件就有答案,那么将不会继续验证第二个条件
位运算符
& | | | ^ | ~ |
---|---|---|---|
与 | 或 | 异或 | 非 |
package operator;
public class Demo06 {
public static void main(String[] args) {
/*
位运算符
A 0100 1101
B 1011 0110
A & B 0000 0100 两个都为1才为1
A | B 1111 1111 有一个为1就为1
A ^ B 1111 1011 相同的为0,不同的为1
~B 0100 1001 与原来的不同
*/
}
}
移位运算符
<< | >> | >>> |
---|---|---|
左移 | 带符号右移 | 无符号右移 |
package operator;
public class Demo07 {
public static void main(String[] args) {
System.out.println(2<<3); //16
System.out.println(16>>1); //8
}
}
将十进制转换成二进制,左移几位就是把高位去掉几位,低位用零补足,负数用1补足
可以理解为左移几位,就是*2的几次方
右移几位,就是/2的几次方
扩展赋值运算符
+= | -+ | *= | /= |
---|---|---|---|
package operator;
public class Demo08 {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println(a+=b);
}
}
条件运算符
? :
package operator;
public class Demo09 {
public static void main(String[] args) {
int score = 80;
String type = score>60 ? "及格" : "不及格";
System.out.println(type);
}
}