运算符
二元运算
package operator;
public class Duality {
public static void main(String[] args) {
//二元运算符
//ctrl+D:复制当前行到下一行
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println(a+b);//30
System.out.println(a-b);//-10
System.out.println(a*b);//200
System.out.println(a/b);//0
System.out.println(a/(double)b);//0.5
System.out.println(a%b);//10 取余
System.out.println("= = == = = = == = = = ");
/*
整数运算:
如果两个操作数有一个为Long, 则结果也为long
没有long时,结果为int。即使操作数全为shot,byte,结果也是int.
浮点运算:
如果两个操作数有一个为double,则结果为double.
只有两个操作数都是float,则结果才为float.
*/
long a1 = 123123123123123L;
int b1= 123;
short c1 = 10;
byte d1 = 8;
float f = 12.3f;
double e = 123.123;
System.out.println(a1+b1+c1+d1);// 123123123123264 long
System.out.println(b1+c1+d1);//141 int
System.out.println(c1+d1);//18 int
//System.out.println((String)(c1+d1));//报错,int转String
System.out.println(a1+b1+c1+d1+e);//1.2312312312338712E14 double
System.out.println(a1+b1+c1+d1+f+e);//1.2312312283148312E14 double
System.out.println(a1+b1+c1+d1+f);//1.23123123E14 float
//幂运算:2^3 math类
double p = Math.pow(2,3);//8.0
System.out.println(p);
}
}
package operator;
//逻辑运算符
public class Ternary {
public static void main(String[] args) {
// 与(&&/&) 或(||) 非(!)
//短路运算 &&
int c = 5;
boolean d = (c<4)&&(c++<7);
System.out.println(d);//false
System.out.println(c);//5 没有执行c++操作
//非短路运算 &
int e = 5;
boolean f = (e<4)&(e++<7);
System.out.println(f);//false
System.out.println(e);//6 执行c++操作
//位运算
/*
* A = 0011 1100
* B = 0000 1101
* A&B = 0000 1100 按位与都1则1(两个都真1,则真1)
* A|B = 0011 1101 按位或都0则0(有一个真1,则真,都假0则假0)
* A^B = 0011 0001 按位异或不同则1,同则0(异则1)
* `B = 1111 0010 按位取反(0改1,1改0)
*面试题:2*8怎么算快
* 2*8 = 16 2*2*2*2
<< *2 左移n位,相当于乘以2^n
>> /2 右移n位,相当于除以2^n
* */
System.out.println(2<<3);//16
System.out.println(10>>3);//1
//扩展运算
int a = 10;
int b = 20;
a+=b;//a = a+b
a-=b;//a = a-b
System.out.println(a);//10
//字符串连接符 + 两侧只要有一方为String类型,都转换成String连接
System.out.println(""+a+b);//1020
System.out.println(a+b+"");//30
//System.out.println((int)(a+b+""));//30报错,Strin转int
//三元运算符 x ? y:z
int x= a<b ? a:b;
System.out.println(x);//10
int y = a<b ? b:a;
System.out.println(y);//20
}
}
优先级
参考链接:https://blog.youkuaiyun.com/pmcasp/article/details/78786966