基本运算符
Java语言支持如下运算符:
- 算术运算符:+, - , *, / , %(取模), ++, --
- 赋值运算符:=
- 关系运算符:>, <, >=, <=, ==, !=instanceof
- 逻辑运算符:&&, ||, !
- 位运算符:&, |, ^, ~, >>, <<, >>>(了解即可)
- 条件运算符:? :
- 扩展赋值运算符:+=, -=, *=, /=
基本运算符的应用
二元运算符
public class Demo01 {
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);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
System.out.println(a/(double)b);
}
}
自动类型转换
public class Demo02 {
public static void main(String[] args) {
long a = 123123123123L;
int b =123;
short c = 10;
byte d = 8;
//有高优先级的数据类型参与运算,自动转换成高优先级的数据类型
System.out.println(a+b+c+d);//Long
System.out.println(a+b+c);//int
System.out.println(c+d);
}
}
关系运算符
public class Demo03 {
//关系运算符返回的结果: 正确,错误 布尔值
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 21;
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a==b);
System.out.println(a!=b);
System.out.println(c%a);//取余这里叫模运算
}
}
关系运算符
public class Demo04 {
public static void main(String[] args) {
//一元运算符 ++ --
int a = 3;
int b = a++;//a在分号结束后+1,复值前a为3之后为4
int c = ++a;//a分号前+1,之后不变
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
逻辑运算符
public class Demo04 {
public static void main(String[] args) {
//一元运算符 ++ --
int a = 3;
int b = a++;//a在分号结束后+1,复值前a为3之后为4
int c = ++a;//a分号前+1,之后不变
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
位运算
public class Demo {
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
>> 右移 右移一位相当于/2
0000 0000 0
0000 0001 1
0000 0010 2
0000 0100 4
0000 1000 8
0001 0000 16
三目运算符和扩展赋值运算符
public class Demo07 {
public static void main(String[] args) {
//三目运算符和扩展赋值运算符
int a = 30;
int b = 20;
a += b;// a = a+b
a -= b;// a= a-b
//字符串连接符 + ,String 注:当存在字符串时,可以直接将字符连接(面试题)
System.out.println(" "+a+b);//如果字符串在前面会进行拼接
System.out.println(a+b+" ");//如果字符串在后面则只会进行运算
}
}
判断条件? 满足条件 : 不满足条件
public class Demo08 {
public static void main(String[] args) {
//x ? y;z (偷懒方法但十分精简好用)
int score = 80;
String type = score<60 ? "不及格":"及格";
System.out.println(type);
}
}