Java运算符拓展
一元运算符
//一元运算符:++(自增);--(自减)
public class Demo01 {
public static void main(String[] args) {
int a = 3;
int b = a++;//先将a的值赋给b,a再自增
//a++就等于a=a+1
System.out.println(a);//4
System.out.println(b);//3
int c = ++a;//a先自增,再将自增后的值赋给c
//++a就等于a=a+1
System.out.println(a);//5
System.out.println(c);//5
int d = a--;//先将a的值赋给d,a再自减
//a--就等于a=a-1
System.out.println(a);//4
System.out.println(d);//5
int e = --a;//a先自减,再将自减后的值赋给e
System.out.println(a);//3
System.out.println(e);//3
}
}
二元运算符
//二元运算符
public class Demo02 {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 21;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / (double)b);
System.out.println(c % a);//取余,模运算
}
}
三元运算符
//三元运算符:x ? y : z(如果x==true,则结果为y,否则结果为z)
public class Demo03 {
public static void main(String[] args) {
int score1 = 80;
int score2 = 50;
String type1 = (score1 > 60) ? "及格" : "不及格";
String type2 = (score2 > 60) ? "及格" : "不及格";
System.out.println(type1);//及格
System.out.println(type2);//不及格
}
}
关系运算符
//关系运算符返回的结果:正确或错误
public class Demo04 {
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
}
}
逻辑运算符
//逻辑运算符:与(&&),或(||),非(!)
public class Demo05 {
public static void main(String[] args) {
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));//如果是真,则变为假;如果是假,则变为真
}
}
位运算符
//位运算符:<<(左移):*2,>>(右移):/2
public class Demo06 {
public static void main(String[] args) {
/*
A = 0011 1100
B = 0000 1101
---------------
A&B 0000 1100 (与)不同为0,相同为1
A/B 0011 1101 (或)有1为1,没1为0
A^B 0011 0001 (异或)相同为0,不同为1
~B 1111 0010 (取反)
*/
System.out.println(2 << 3);//16
System.out.println(9 >> 3);//1
}
}
幂运算
//幂运算:(很多运算,我们会使用一些工具类来操作!)
public class Demo07 {
public static void main(String[] args) {
double pow = Math.pow(2,3);//2^3(2*2*2)
System.out.println(pow);//8.0
}
}
短路运算
//短路运算标签:Java,int,System,拓展,运算符,println,public,out From: https://www.cnblogs.com/my-ytt/p/16906613.html
public class Demo08 {
public static void main(String[] args) {
int a = 5;
boolean b = (a < 4) && (a++ < 4);//a=5>4造成短路,不执行后面那部分
System.out.println(a);//5
System.out.println(b);//false
boolean c = (a > 4) && (a++ > 4);
System.out.println(a);//6
System.out.println(c);//true
}
}