1、名词解释
&称为逻辑与,会全部判断后得出结果,只有两个操作数都是true,结果才是true
&&称为短路与,会从左往右逐个判断表达式,只要能得出结果后面的不再判断,也是只有两个操作数都是true,结果才是true。但是如果左边操作数为false,就不计算右边的表达式,直接得出false,相当于短路了右边
|称为逻辑或,||称为短路或,道理类似
2、举例说明
(1)逻辑或逐个判断表达式,因此以下代码会抛出异常NullPointerException
String a = null;
if(a == null || a.length() == 0){
System.out.println("true");
}
if(a == null | a.length() == 0){ // 抛出异常
System.out.println("true");
}
(2)移位运算
int number = 7;
//原始数二进制
System.out.println(Integer.toBinaryString(number));
System.out.println(number);
//右移一位(相当于除以2,但不是绝对,例如本例中:7向右移动一位,结果为3)
number = number >> 1;
System.out.println(Integer.toBinaryString(number));
System.out.println(number);
//左移一位(相当于乘以2,例如本例中:3向左移动一位,结果为6)
number = number << 1;
System.out.println(Integer.toBinaryString(number));
System.out.println(number);
(3)整型数和网络字节序的byte[]数组之间的转换
public static byte[] longToBytes(long n) {
byte[] b = new byte[8];
b[7] = (byte) (n & 0xff);
b[6] = (byte) (n >> 8 & 0xff);
b[5] = (byte) (n >> 16 & 0xff);
b[4] = (byte) (n >> 24 & 0xff);
b[3] = (byte) (n >> 32 & 0xff);
b[2] = (byte) (n >> 40 & 0xff);
b[1] = (byte) (n >> 48 & 0xff);
b[0] = (byte) (n >> 56 & 0xff);
return b;
}
public static long bytesToLong( byte[] array )
{
return ((((long) array[ 0] & 0xff) << 56)
| (((long) array[ 1] & 0xff) << 48)
| (((long) array[ 2] & 0xff) << 40)
| (((long) array[ 3] & 0xff) << 32)
| (((long) array[ 4] & 0xff) << 24)
| (((long) array[ 5] & 0xff) << 16)
| (((long) array[ 6] & 0xff) << 8)
| (((long) array[ 7] & 0xff) << 0));
}