Java语言支持的运算符:
运算的优先级:加减乘除,先乘除,后加减。在程序中括号()里面的优先级最大。
算术运算符 | +,-,*,/,%(模运算相当于取余),++,- - |
---|---|
赋值运算符 | = |
关系运算符 | >, <, >=, <=, ==, !=, instance of |
逻辑运算符 | &&(并),II(或),!(非) |
位运算符 | &,I,^,~,>>,<<,>>>(了解就好!) |
条件运算符 | ?,: |
扩展赋值运算符 | +=,-=,*=,/= |
算术运算符
public class Operator {
public static void main(String[] args) {
//二元运算符
//ctrl+D 复制到下一行
int a =22;
int b =10;
long c = 123456789;
int d = 123;
short e = 15;
byte f = 5;
System.out.println(a+b);//a+b的值
System.out.println(a-b);//a-b的值
System.out.println(a*b);//a*b的值
System.out.println(a/b);//a/b的值
System.out.println(a%b);//a%b相当于a除以b的余数值2
System.out.println(c+d+e+f);//输出结果为long类型
System.out.println(d+e+f);//int类型
System.out.println(e+f);//int类型
//有比int级高的就输出高级类型的数据
//其余的数据类型相加都为int型
}
}
关系运算符
public class Operator {
public static void main(String[] args) {
//关系运算符的返回结果:为布尔值 true或 false
int a = 10;
int b = 20;
System.out.println(a>b);//输出结果:false
System.out.println(a<b);//输出结果:ture
System.out.println(a==b);//输出结果:false
System.out.println(a!=b);//输出结果:ture
}
}
自增(++)和自减(- -)
public class Operator {
public static void main(String[] args) {
//++ -- 一元运算符
int a =15;
int b =a++;//a++就相当于先赋值给b,然后在自增
//a = a + 1;
System.out.println(a);//输出结果为16
//a = a + 1;
int c =++a;
System.out.println(a);//输出结果为17
System.out.println(b);//输出结果为15
System.out.println(c);//输出结果为17
}
}
幂运算
public class Operator {
public static void main(String[] args) {
//很多运算,我们会使用一些工具类操作下面所用为Math类
double pow =Math.pow(2,3);//表示2的3次方
System.out.println(pow);//输出结果为8.0
}
}
逻辑运算
public class Operator {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("a && b:"+(a&&b));//输出结果为a && b:false
//两个变量都为真,结果才为真。其余都为假。
System.out.println("a|| b:"+(a||b));//输出结果为a|| b:true
//两个变量只要有一个为真,结果就为真,其余都为假。
System.out.println("!(a && b):"+!(a && b));//输出结果为!(a && b):true
//如果是真,则变为假。如果是假,则变为真。
}
}
短路运算
public class Operator {
public static void main(String[] args) {
int a = 6;
boolean b = (a<4)&&(a++<4);
//如果第一个(a<4)为假则将不运行a++<4
System.out.println(b);//输出结果为false
System.out.println(a);//输出结果为6,如果不短路的话a=7
}
}
位运算(效率极高)
public class Operator {
public static void main(String[] args) {
/*
A=0011 1100
B=0000 1101
------------------
A&B(并)=0000 1100
A|B(或)=0011 1101
A^B(异或)=0011 0001
~B(非)=1111 0010
--------------------------
2*8怎么运算最快?16
拆分为2*2*2*2
<< (左移)为 乘以2
>>(右移)为 除以2
*/
System.out.println(2<<3);//结果为16
System.out.println(3<<2);//结果为3*2*2=16
System.out.println(48>>4);//48/2/2/2/2=3
}
}
扩展赋值运算
public class Operator {
public static void main(String[] args) {
int a = 10;
int b = 20;
a+=b; //a=a+b
a-=b; //a=a-b
System.out.println(a);
//字符串的连接符 + ,String
System.out.println(""+a+b);//输出结果为1020
//如果字符串在前面,后面的就会拼接
System.out.println(a+b+"");//输出结果为30
//如果字符串在后面,前面的正常计算
}
}
条件运算符
public class Operator {
public static void main(String[] args) {
//三元运算符
// x ? y : z
//如果x==true,则结果为 y ,否则结果为 z 。
int score = 70;
String type = score<60 ? "不及格":"及格";
System.out.println(type);
}
}