运算符
运算符
Java 语言支持如下运算符 :
- 算数运算符 : + , - , ***** , / , % , ++ , **-- **
- 赋值运算符 : =
- 关系运算符 : > , < , >= , <= , == , != instanceof
- 逻辑运算符 : && , || , !
- 位运算符 : & , | , ^ , ~ , >> , << , >>> (了解! ! !)
- 条件运算符 ? :
- 扩展赋值运算符 : += , -= , *= , /=
一元运算符
- ++ -- : 自增,自减
public class Demo04 {
public static void main(String[] args) {
int a = 3;
int b = a++;//执行完这行代码后,先给b赋值,再自增
//a = a + 1;
System.out.println(a);//a=4
int c = ++a;//执行完这行代码前,先自增,再给c赋值
//a = a + 1;
System.out.println(a);//a=5
System.out.println(b);//b=3
System.out.println(c);//c=5
二元运算符
- + - * / %(取余,模运算)
public class Demo02 {
public static void main(String[] args) {
long a = 1212121212121212121L;
int b = 12312123;
short c = 12345;
byte d =127;
System.out.println(a+b+c+d);//输出结果为1212121212133536716
System.out.println(b+c+d);//输出结果为12324595
System.out.println(c+d);//输出结果为12472
a+=b;// a=a+b
a-=b;// a=a-b
int e = 20;
int f = 21;
System.out.println(f%e);//输出结果为1 (21/20=2余1)
}
}
- 输出结果默认为int类型
- 输出结果会自动转换(低->高 byte short char int long float double)取算式中优先级最高的数据类型,小于int则为默认
三元运算符
- x ? y : z : 如果x=true,则结果为y,否则结果为z;
public class Demo08 {
public static void main(String[] args) {
int score = 80;
String type = score < 60 ? "不及格" : "及格";//必须掌握
//if
System.out.println(type);//输出结果为及格
}
}
关系运算符
- 关系运算符返回结果:正确,错误(布尔值)
public class Demo3 {
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
System.out.println(a!=b);//输出结果为true
}
}
逻辑运算符
- && || !( && ) : 与(and) 或(or) 非(取反)
public class Demo05 {
public static void main(String[] args) {
// 与(and) 或(or) 非(取反)
boolean a = true;
boolean b = false;
System.out.println("a && b:"+(a&&b));//逻辑与运算: 两个变量都为真,结果才为true
System.out.println("a || b:"+(a||b));//逻辑与运算: 两个变量有一个为真,结果为true
System.out.println("!(a && b):"+!(a&&b));//如果为真则为假如果为假则为真(两个变量有一个为真结果为真,两个变量都为真结果为假,两个变量都为假结果为真)
int c = 5;
boolean d = (c<4)&&(c++<4);
System.out.println(d);//结果为false
System.out.println(c);//结果为5
//在运行&&中,如果前半段为false则停止对后半段的运行
}
}
- & | ^ ~ : 与 或 异 非(二进制运算符)
A = 0011 1100
B = 0000 1101
A&B = 0000 1100//有一个为0则为0
A|B = 0011 1101//有一个为1则为一
A^B = 0011 0001//相同为0否则为1
~B = 1111 0010//为0为1,为1为0
字符串连接符
- [空格]+
public class Demo07 {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println(""+a+b);//输出结果为1020
System.out.println(a+b+"");//输出结果为30
System.out.println(a+b+""+a+b);//输出结果为301020
}
}
- 当运行到字符串连接符时,后面以字符输出
位运算符
- << >> : *2 /2
public class Demo06 {
public static void main(String[] args) {
int a = 1;
System.out.println(a<<1);//输出结果为2=1*2
System.out.println(a<<2);//输出结果为4=1*2*2
System.out.println(a<<3);//输出结果为8=1*2*2*2
}
}
- 二进制效率极高
幂运算
- 很多运算,我们会使用一些工具来操作!
public class Demo04 {
public static void main(String[] args) {
double pow = Math.pow(3,3);//输出结果为27=3^3=3*3*3
System.out.println(pow);
}
}

浙公网安备 33010602011771号