常用运算符
运算符
java语言支持如下运算符:
- 算术运算符:+,-,*,/,%,++,--
- 赋值运算符 =
- 关系运算符:>, <, >=, <=, == , !=, instanceof
- 逻辑运算符:&&,||,!
- 位运算符: & , |,
加减乘除
public class Demo01 {
public static void main(String[] args) {
long a = 12343344330L;
int b = 123;
short c = 10;
byte d = 8;
System.out.println((long) a+b+c+d);//Long
System.out.println(b+c+d);//int
System.out.println((int)c+d);//int
// System.out.println(a+b+c+d);
}
}
关系运算
public class Demo03 {
public static void main(String[] args) {
//关系运算符返回的结果:正确、错误。 是个布尔值。
// 和 if一起使用的多。
int a = 10;
int b = 20;
int c = 21;
System.out.println(c%a); //取余,也叫模运算
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a==b);
System.out.println(a!=b);
}
}
自增自减运算
public class Demo04 {
public static void main(String[] args) {
// ++ -- 自增,自减 一元运算符
int a = 3;
int b = a++; //先将a的值赋予给b,然后自增;
//a++ 相当于 a = a + 1;加之前,将值赋予给b了。
System.out.println(a);
System.out.println("========================");
int c = ++a; //先自增,再将a的值赋予给c;
//++a 相当于 a = a + 1;加之后,将值赋予给c。
System.out.println(a);
System.out.println(b);
System.out.println(c);
//幂运算 2的3次方
double pow = Math.pow(3,2);
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)); //逻辑与运算:两个变量都为真,结果才为ture
System.out.println("a || b:"+(a||b));
System.out.println("!(a && b)"+!(a&&b));
//短路运算
int c = 5;
boolean d =(c<6)&&(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 //A和B的位置,求交集,必须都为1,结果是1,反之为0;
A|B 0011 1101 //A和B的位置,求并集,只要有一个为1,结果是1,反之为0;
A^B 0011 0001 //异或运算,A和B值相同(不管值为0还是1,只要值相同)就为0,不同则为1;
~B 1111 0010 // 取反;
2*8 怎么运算最快?
拆分成2*2*2*2最快。
左移:<< 相当于把数字乘以2;
右移:>> 相当于把数字除以2;
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 0101 5
0000 0110 6
0000 0111 7
0000 1000 8
*/
System.out.println(2>>3);
System.out.println(2<<3);
}
}
扩展赋值运算符
public class Demo08 {
public static void main(String[] args) {
int a = 10;
int b = 20;
a+=b; // a = a+b;
System.out.println(a);
a-=b; // a = a-b;
System.out.println(a);
//字符串连接符. 字符串在前面+输出,会先拼接; 字符串在后面会先计算;
System.out.println(b+b);
System.out.println(""+a+b); //先拼接,输出1020
System.out.println(a+b+""); //先计算,输出30
}
}
条件运算符
public class Demo09 {
public static void main(String[] args) {
/*/三元运算符: x ? y: z
如果x为true,则结果等于y;否则等于z;
*/
int score = 50;
String type = score < 60 ? "fail" : "pass"; // 必须掌握
System.out.println(type);
int h = 13;
String en = h<14?"short":"long";
System.out.println(en);
}
}
浙公网安备 33010602011771号