运算符
java语言支持如下运算符
-
算术运算符:+、-、*、%(取余 模运算)、++、--
-
赋值运算:=
-
关系运算符:> 、<、 >= 、 <= 、 == 、 != 、instanceof
-
逻辑运算符:&&(与)、||(或)、!(非)
-
-
条件运算符 ? :
-
扩展赋值运算:+=、-=、*=、/=
package operator;
public class Deom01 {
public static void main(String []args){
//二元运算符
int a =10;
int b =20;
int c =25;
int d =30;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/(double)b);//因为有小数,直接取整数,变成 0 所以要强制转换下
}
}
package operator;
public class Demo02 {
public static void main(String[] args) {
long a=1231232112221L;
int b=123;
short c =10;
byte d =8;
System.out.println(a+b+c+d);//Long
System.out.println(b+c+d);//Int
System.out.println(c+d);//Int
System.out.println((double)c+d);//Int
}
}
package operator;
public class Demo03 {
public static void main(String[] args) {
//关系运算符返回结果 :false true 布尔值
//if
int a = 10;
int b = 20;
int c = 21;
System.out.println(c%a);// c/a 21/10=2......1 取余数1
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a==b);
System.out.println(a!=b);
}
}
package operator;
public class Demo04 {
public static void main(String[] args) {
// ++ -- 自增 自减 一元运算符
int a = 3;
int b = a++;//a++ a=a+1 在这里b 先被赋值 b=3 然后a在自加1 所以 a=4 输出a=4
System.out.println(a);//a=4
System.out.println(b);//b=3
int c = ++a;//在这 a先自加 所以 a=4+1=5 然后c在被赋值 c=5
System.out.println(a);//a=5
System.out.println(c);//c=5
System.out.println(a);
System.out.println(b);
System.out.println(c);
//幂运算 2^3 2*2*2=8 很多运算 我们会使用一些工具类来操作
double pow = Math.pow(2, 5);// 输入 Math.pow(2, 3)然后按住 alt+enter
System.out.println(pow);
}
}
package operator;
//逻辑运算符
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" +(b && a)); 短路运算 因为b直接就是假的了
System.out.println("a || b"+(a || b));// 逻辑或运算:两个变量有一个为真,结果就可为 true
System.out.println("! (a && b)"+! (a && b));//逻辑非运算:如果是真,则为家,反之亦然。
//短路运算
int c = 5;
boolean d = (c<4)&&(c++<4);//输出 c= 5 false 因为在这里 c<4 已经是false了 就没必要进行后面的运算了
// boolean d = (c>4)&&(c++<4); 输出 c= 6 false
System.out.println(c);
System.out.println(d);
}
}
package operator;
//位运算符
public class Demo06 {
public static void main(String[] args) {
/*
A = 0011 1100
B = 0000 1101
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001 //异或 :相同为0 不同为1
~B = 1111 0010 //取B的反
2*8 如何能快速运算 ? 2*2*2*2=16
<< 左移 *2
>> 右移 /2
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16
*/
System.out.println(2<<3);
}
}
浙公网安备 33010602011771号