Java基础之基本运算符
基本运算符
- 算数运算符:+、-、*、/、%、++、--
- 赋值运算符:=
- 关系运算符:>、<、>=、<=、==、!= instanceof
- 逻辑运算符:&&、||、!
- 位运算符:&、|、^、~、>>、<<、>>>(了解)
- 条件运算符:?
- 扩展赋值运算符:+=、-=、*=、/=
注:在IDEA中,Ctrl + D,将上一行中的内容复制到下一行。
自增自减运算符
int a = 3;
int b = a++; //执行完这行代码后,先给b赋值,再自增,b=3,a=4
//a = a + 1;
System.out.println(a);//4
//a = a + 1;
int c = ++a; //执行完这行代码前,先自增,再给c赋值,a=5,c=5
System.out.println(a);
System.out.println(b);
System.out.println(c);
Math类
//很多运算,我们会使用一些工具类来操作
//幂运算 2^3 = 8;
double pow = Math.pow(2,3);//Math类
System.out.println(pow); //8.0
逻辑运算符
//逻辑运算符:与(and) 或(or) 非(取反)
boolean a = true;
boolean b = false;
System.out.println("a && b:"+(a&&b)); //false 逻辑与运算:两个变量都为真,结果才为true
System.out.println("a || b:"+(a||b)); //true 逻辑与运算:两个变量有一个为真,结果才为true
System.out.println("!(a && b):"+!(a&&b)); //true 如果是真,则变为假,如果是假,则变为真
//短路运算
int c = 5;
boolean d = (c < 4)&&(c++ <4) ;//c++ <4 未执行
System.out.println(d);//false
System.out.println(c);//5:c++ <4 未执行
位运算符
public class Demo05 {
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) >> 右移(/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); //8
}
}
public class Demo06 {
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);//10
//字符串连接符 +
System.out.println(""+a+b);//1020 字符串在前面,后面的全部变为字符串进行拼接
System.out.println(a+b+" ");//30
}
三元运算符
public class Demo07 {
public static void main(String[] args) {
//x ? y : z
//如果x==true,则结果为y,否则结果为z
int score = 80;
String type = score < 60 ?"不及格":"及格";
System.out.println(type);//及格
}
每根烟都只是在缓解药物戒断症状,不能带来别的东西。......我不希望在凌晨3点看到接上生命维持器的你,我不希望告诉你的家人你是死于吸烟。——《重症监护室的故事》
@侧耳听智慧,专心求聪明 Turnging your ear to wisdom and applying your heart to understanding!

浙公网安备 33010602011771号