运算符
- java语言支持以下的运算符
- 算术运算符 +、-、*、/、%、++、–
- 赋值运算符=,+=,-=、*=、/=
- 关系运算符. >,<,>=,<=、==、!=、instanceof
- 逻辑运算符&&、||、!
- 位运算符:&、|、^、>>、<<
- 条件运算符(三木运算):? :
//算术运算注意点和面试常考——byte、++、--
public class Base2 {
public static void main(String[] args) {
long a = 1234567L;
int b = 12;
short c = 2;
byte d = 1;
System.out.println(a+b+c+d);//long
System.out.println(a+c+d);//int
//byte参与运算的时候,先转换成int型 再进行计算
System.out.println(c+d);//int
System.out.println(c+c);//short ,short运算不会先转换为int
byte b1=3,b2=4,e;
e = b1+b2;//会发生错误,应该改为 e = (byte)(b1+b2)
// ++ 自增 -- 自减
int a = 3;
//先赋值后加减,要int b = ++a;z这句执行过后再+1
int b = a++;
//先加减后赋值
int c = ++a;
System.out.println(a);//5
System.out.println(b);//3
System.out.println(c);//5
}
}
//幂运算 2^3= 2*2*2 = 8,使用工具类操作
double pow = Math.pow(2,3);
//与(and) 或(or) 非(取反)
boolean a = true;
boolean b = false;
System.out.println("a && b:"+(a&&b));//false
System.out.println("a || b:"+(a||b));//true
System.out.println("!(a && b):"+!(a&&b));//true
//其中注意&& ||是短路与和短路非
//短路与&& 当&&前面表达式为false,则不判断后面的表达式
//短路|| 当||前面表达式为true,则不判断后面的表达式
//位运算
/*A = 0000 0011;
B = 1100 1000;
---------------------------------
A&B = 0000 0000;
A|B = 1100 1011;
A^B = 1100 1011;
~B = 0011 0111;
*/
//因此2^3快速运算可以使用位运算
//<< *2
//>> /2
int a = 2<< 3;
//字符串连接符
int a = 1;
int b = 2;
system.out.println(""+a+b);//12 前面有" "将转换为字符串拼接
system.out.println(a+b+" ");//3 后面“”不影响运算
注意:运算的优先级可以由()改变