Thinking in Java [Java编程机制] 学习笔记 -- 操作符Operator

Thinking in Java [Java编程机制] 学习笔记 -- 操作符Operator

1.第一个要说明的操作符,就是"=="

注意事项1:

如果是两个引用间使用==,比较的是两个引用,无论所引用对象的值是否相同。所以在比较Integer,String的值的时候,强烈建议要使用equals.
但是什么时候比较String可以用==呢,这有一个例子,引用于Here
// These two have the same value
new String("test").equals("test") ==> true 

// ... but they are not the same object
new String("test") == "test" ==> false 

// ... neither are these
new String("test") == new String("test") ==> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" ==> true 

// concatenation of string literals happens at compile time resulting in same objects
"test" == "te" + "st"  ==> true

// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) ==> false

注意事项2:

double和float大小比较。比较double和float的时候要避免使用==和!=。原因是浮点数是有精度的,精度就是double或者float所能表示的最小的那个数。
举个例子,
double d1=0.1f;
double d2=0.1;
d1和d2是不相等的,因为0.1恰好不能被double的精度整除。所以我们比较时通常使用一个很小的浮点数作为精度单位

2. 位操作符当中的移位操作符 ">>",  "<<" 以及 ">>>"

说明“0xffffffff是-1;  0x10000000是最大的负数”

左移位:<<,有符号的移位操作
左移操作时将运算数的二进制码整体左移指定位数,左移之后的空位用0补充。
Java中左移的具体操作和符号位是1和是0没有关系,无论是正数还是负数,左移后都会乘以2. 所以最小的负数如果左移1位,会溢出得0. 
例如 
int n1 = 0x80000000;
int n2 = n1 << 2;
n1 : 0x00000000

右移位:>>,有符号的移位操作

右移操作是将运算数的二进制码整体右移指定位数,右移之后的空位用符号位补充,即如果是正数用0补充,负数用1补充.
int n1 = 0x80000000;
int n2 = n1 >> 2;
n1 : 0xE0000000


无符号的移位只有右移,没有左移使用“>>>”进行移位,都补充0
int n1 = 0x80000000;
int n2 = n1 >> 2;
n1 : 0x20000000



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章