逻辑运算符
- 逻辑运算符 &&, ||, !。
- && 有一个为假,则为假
- || 有一个为真,则为真
- ! 非
package operator;
public class Demo1 {
public static void main(String[] args) {
//逻辑运算符 && || !
/*
&& 有一个为假,则为假
|| 有一个为真,则为真
! 非
**/
//短路运算
int a=5;
boolean b=(a<4)&&(++a>5);//只要前边条件错误,后边就不再执行。
System.out.println(b);
System.out.println(a);
boolean c=false;
boolean d=true;
System.out.println("c&&d:"+(c&&d));
System.out.println("c||d:"+(c||d));
System.out.println("!(c&&d):"+!(c&&d));
}
}
运行结果:
false
5
c&&d:false
c||d:true
!(c&&d):true
位运算符
A =0011 1100
B =0000 1101
A&B=0000 1100
A|B=0011 1101
~B=1111 0010
怎样算2*8最快? 位运算
<<左移 *2
>>右移 /2
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16
由此可见乘2,相当于左移1位。
package operator;
public class Demo2 {
public static void main(String[] args) {
//位运算符
/*
A =0011 1100
B =0000 1101
A&B=0000 1100
A|B=0011 1101
~B=1111 0010
面试:怎样算2*8最快? 位运算
<<左移 *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);//左移3位 2*2^3
System.out.println(16>>2);
}
}
运行结果:
16
4
三元运算符
-
三元运算符
x ? y : z 如果x为真,则执行y;否则执行y。
package operator;
public class Demo3 {
public static void main(String[] args) {
//字符串连接符 + ,如果有一侧为String类型,则会将另一侧的操作数转换为String类型再连接
int a = 10;
int b = 20;
//面试,""+ 与 +"" 区别
System.out.println("" + a + b);
System.out.println(a + b + "");//如果""在后面,前方依旧会进行运算
//三元运算符
// x ? y:z 如果x为真,则执行y;否则执行y
int score = 70;
String type = score > 60 ? "及格" : "不及格";
String type1 = score > 80 ? "及格" : "不及格";
System.out.println(type);
System.out.println(type1);
}
}
运行结果:
1020
30
及格
不及格