运算符
运算符
-
算数运算符
//+,-,*,/,%,++,--
public class Demo01{
public static void main (String[]args){
long a= 123123123132123L;
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
}
}
注:输出变量中只要有一个是long或者double类型,则输出结果也为long或者double.如果没有long/double,则输出结果为int类型。
特别注意:自增和自减++,--
public class Demo02{
public static void main(String[]args){
int a= 3;
int b= a++;//执行完这行代码后,先给b赋值(相当于b=a),a再自增
int c= ++a;//执行完这行代码前,a先自增,再给c赋值(相当于c=5)
system.out.println(a);
system.out.println(b);
system.out.println(c);
}
}
-
赋值运算符
//a=b; 把b赋值给a
-
关系运算符
//>,<,>=,<=,==,!=instanceof
public class Demo02{
public static void main(String[]args){
int a= 10;
int b= 20;
int c= 22;
system.out,println(c%a);//c除以a:22/10=2...2
system.out,println(a>b);//大于
system.out,println(a<b);//小于
system.out,println(a==b);//等于
system.out,println(a!=b);//不等于
}
}
-
逻辑运算符
//&&,||,!(取反)
public class Demo03{
public static void main(String[]args){
boolean a= true;
bollean 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));//逻辑非:如果是真,则为假。反之,为真
}
}
-
位运算符
&,|,^(异或),~,>>(往左),<<(往右),>>>
public class Demo04{
public static void main(String[]args){
/*
A = 0011 1100
B = 0000 1101
----------------------------------
A&B=0000 1100
A|B=0011 1100
A^B=0011 0011
~B= 1111 0010
*/
//面试题 2*8=16
/*
<< *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);
}
}
-
条件运算符
*很重要!!!
//三元运算符 public class Demo05{ public static void main(String[]args){ //x?y:z 如果x==true,则结果为y,否则结果为z int score= 50; String type =score <60?"不及格":"及格"; system.out.println(type); } }
运行结果为不及格
-
扩展赋值运算符
+=,-=,*=,/= a+=b;//a=a+b a-=b;//a=a-b
拓展
- 初识math类
//幂运算 2^3=8在java中应该如何计算
double pow=Math.pow(2,3);
system.out.println(pow);
运行结果为8.0
2.短路运算
int c= 5;
boolean d= (c<4)&&(c++<4);//当c<4为错误的后面根本再不会继续执行
system.out.println(d);
system.out.println(c);
运行结果为false 5
3.字符串连接符
//加号前面是String字符串类型,加号在前和在后结果不同
system.out.println(""+a+b);//字符串在前面,直接拼接
system.out.println(a+b+"");