运算符
基本运算符
二元运算符
- +,-,*,/
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
System.out.println(a/b); //0
}
}
整型运算返回数据的类型
-
数据中有long时自动返回long类型的数据
-
其他的一律返回成int类型的数据
public class Demo02 {
public static void main(String[] args) {
long a = 123123123123L;
int b = 123;
short c = 10;
byte d = 8;
/*
用long就返回long,没有就返回int
*/
System.out.println(a+b+c+d); //123123123264 long
System.out.println(b+c+d); //141 int
System.out.println(c+d); //18 int
}
}
关系运算符
- 关系运算符返回的结果 真或假 布尔值
public class Demo03 {
public static void main(String[] args) {
//关系运算符返回的结果 真或假 布尔值
int a = 10;
int b = 20;
System.out.println(a>b); //false
System.out.println(a<b); //true
System.out.println(a==b); //false
}
}
使用数学工具进行运算
- 例如Math.pow用来计算多少次方
//2^3=8
public class Demo04 {
public static void main(String[] args) {
double pow = Math.pow(2, 3);
System.out.println(pow);
}
}
逻辑运算符
- && || !
- 短路运算
public class Demo05 {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("a && b: "+(a && b));
System.out.println("a || b: "+(a || b));
System.out.println("! (a && b): "+!(a && b));
//短路运算
int c=5;
boolean d = (c<4) && (c++>4);
System.out.println(d);
System.out.println(c);
}
}
位运算符
public class Demo06 {
public static void main(String[] args) {
/*
A = 0011 1100;
B = 0000 1101;
---------------
A&B = 0000 1100; 用&运算符时 都为1则为1
A|B = 0011 1101; 用|运算符时 都为0则为0
A^B = 0011 0001; 用^运算符时 相同为0,不同为1
~B = 1111 0010; 用~运算符时 取反
---------------
效率极高
<< *2
>> /2
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16
*/
System.out.println(2<<3); //2*2*2*2
}
}
扩展赋值运算符
- +=,-=,*=,/=
- a+=b 等价于 a=a+b
- 字符串连接符
public class Demo07 {
public static void main(String[] args) {
int a = 10;
int b = 20;
a+=b; //a=a+b;
a-=b; //a=a-b;
System.out.println(a); //10
//字符串连接符 + String
//将后面的值转化为字符串形式
System.out.println(""+a+b); //1020
System.out.println(a+b+""); //30
}
}
条件运算符
-
x ? y : z
-
如果x==true,则结果为y;否则为z
//三元运算符
public class Demo08 {
public static void main(String[] args) {
//x ? y : z
//如果x==true,则结果为y;否则为z
int score = 50;
String type = score < 60 ? "不及格" : "及格";
System.out.println(type);
}
}