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



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