逻辑运算符的基本用法
逻辑运算符有哪些
- &(并且) ,
- |(或者) ,
- !(非) ,
- ^(异或) ,
- &&(短路与) ,
- ||(短路或)
注意事项:
逻辑运算符一般用于连接boolean类型的表达式或者值。
用法:
- &逻辑与:有false则false。
- |逻辑或:有一端为true则为true
- ^逻辑异或:相同为false,不同为true。
- !逻辑非:非false则true,非true则false。
代码演示
public class pp {
public static void main(String[] args) {
int a = 10;
int b = 20;
boolean flag = a > b & a > 10;
boolean flag2 = a > 10 | b < 50;
boolean f = !(10 > 5);
boolean ff = false ^ false;
System.out.println(flag);
System.out.println(flag2);
System.out.println(f);
System.out.println(ff);
}
}
ps:
(这里要区分&&与&的区别虽然最终结果一样但是&&具有短路效果,运算更快也就是说左边是false右边不执行)
代码演示
public class ff {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 2;
boolean flag = a != 10 && (b++) > 10;
System.out.println("falg: " + flag);
System.out.println("b: " + b);
// && 当左端为false 右端的表达式就不运算 & 不管左端是什么,两端的表达式都会去执行
//&& 只要左边为true时,右端还是要执行的。
位运算符的基本用法
位运算符有那些
- &(与),
- |(或),
- ^(异或) ,
- ~(按位取反) ,
- <<(左移) ,
- >>(右移) ,
- >>>(无符号右移)
注意事项:
位运算是直接对二进制补码进行运算。
代码演示
public class ff{
public static void main(String[] args) {
int a = 3;
int b = 4;
System.out.println(a & b);// &:有0则0
System.out.println(a | b);//|:有1则1
System.out.println(a ^ b); //^:相同则0,不同则1
System.out.println(~3);//
System.out.println(3 >> 2);//正数 右移动丢弃右边两个bit位 高位补2个0 注意负数高位补 1
System.out.println(3 << 2);// 00001100 <<:左移 空位补0,被移除的高位丢弃。
System.out.println(-3>>>2);//不管正负,高位都补0
注意<<,>>的运算用法
<< : 把<<左边的数据乘以2的移动次幂 例如 10<<3 结果 10*2^3=80
<< : 把>>左边的数据除以2的移动次幂 例如 40>>3 结果 40/2^3=5
如何用一个中间变量交换两个数的值代码演示;
public class ff {
public static void main(String[] args) {
int a=10;
int b=20;
int t=a;
a=b;
b=t;
System.out.println("a:"+a);
System.out.println("b:" + b);
三元运算符的基本用法
- 三元(三目)运算符的格式
(关系表达式) ? 表达式1 : 表达式 - 三元运算符的执行流程 计算关系表达式的值&#