运算符
与(&&) 或(||) 非(!)
public class day3{
public static void main(String[ ] agrs){
boolean a=true;
boolean b=false;
System.out.println("a && b:"+(a&&b));//两个为真才为真
System.out.println("a || b"+(a||b));//一个为真则为真
System.out.println("!(a && b):"+!(a&&b));//若是真则变为假,若是假则变为真
}
}
//结果
a && b:false
a || btrue
!(a && b):true
(1)注意短路运算
System.out.println("a && b:"+(b&&a));
//若a与b发生了位置调换,由于b为假,则后面的步骤不再运算,此时发生短路问题。
//举例:
public class day3{
public static void main(String[ ] agrs){
int c=5;
boolean d=(c<4)&&(c++<4);
System.out.println(d);
System.out.println(c);
}
}
//结果
false
5 //c的结果本应该为6,短路使得c=c+1无法运算
二、位运算 (效率极高)
(1)& 、 / 、 ^ 、 ~的使用
public class day3{
public static void main(String[ ] agrs){
A = 0011 1100
B = 0000 1101
A&B=0000 1100(对应位比较,都是1则为1,否则为0)
A/B=0011 1101(对应位比较,都是0则为0,否则为1)
A^B=0011 0001(对应位比较,相同为0,不同为1)
~B =1111 0010(取反,与之相反)
?提问:2*8在计算机如何运算最快?
答:2*2*2*2
(2)左移<< 右移>>
左移<< = *2
右移>> = /2
//举例:2左移3位=16 System.out.println(2<<3);
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16
三、赋值运算符
a+=b; //a=a+b
a-=b; // a=a-b
面试题:
//字符串连接符 + ,String类型
System.out.println(""+a+b);
System.out.println(a+b+"");
//输出:
1020 //字符串""在前面,a b拼接
30 //字符串""在后面,a b相加
四、三元运算符
x ? : y : z 若x为真,则y,否则z。

浙公网安备 33010602011771号