Thinking in Java [Java編程機制] 學習筆記 — 操作符Operator

來源:互聯網
上載者:User
文章目錄
  • 注意事項1:
  • 注意事項2:
Thinking in Java [Java編程機制] 學習筆記 -- 操作符Operator1.第一個要說明的操作符,就是"=="注意事項1:
如果是兩個引用間使用==,比較的是兩個引用,無論所引用對象的值是否相同。所以在比較Integer,String的值的時候,強烈建議要使用equals.
但是什麼時候比較String可以用==呢,這有一個例子,引用於Here
// These two have the same valuenew String("test").equals("test") ==> true // ... but they are not the same objectnew String("test") == "test" ==> false // ... neither are thesenew 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.