Java 位元運算(移位、位與、或、異或、非)與邏輯運算

來源:互聯網
上載者:User

標籤:i++   als   異常處理   ++   int   左移   amp   boolean   選擇   

java 位元運算包括:左移( << )、右移( >> ) 、無符號右移( >>> ) 、位與( & ) 、位或( | )、位非( ~ )、位異或( ^ ),除了位非( ~ )是一元操作符外,其它的都是二元操作符。

邏輯運算子&、&&、|、||:

一、邏輯&與短路&&的區別
  • 總的來說區別是體現在,只有這兩個運算子的左邊為false的時候會有區別,看如下代碼

1.邏輯&的運算

boolean a = true;boolean b = false;int i = 10;if(b&(i++)>0) System.out.print(i); //輸出11,即&的右邊有進行運算else System.out.print(i);

2.短路&&的運算

boolean a = true;boolean b = false;int i = 10;if(b&&(i1++)>0) System.out.print(i); //輸出10,即&&的右邊沒有運算else System.out.print(i);

小結一下: 
&:不管&的左邊是true還是false,右邊都會進行運算 
&&: 只要左邊是false,右邊就不會進行運算 
一半情況下都會選擇&&,因為這樣可以提高效率,也可以進行異常處理,當右邊產生異常的時候,同樣可以跳過。

二、邏輯| 與短路||的區別
  • 和上面的類似,只不過這兩者是只有當左邊為true的時候,才會有區別,看如下代碼

1.邏輯 | 的的運算

boolean a = true;int i = 10;if(a|(i++)>0) System.out.print(i); //輸出11,即的右邊有進行運算else System.out.print(i);

2.短路 || 的運算

boolean a = true;int i = 10;if(a||(i++)>0) System.out.print(i); //輸出10,即||的右邊沒有運算else System.out.print(i);

小結: 
| : 當左邊為true時,右邊同樣進行運算 
|| : 當左邊為true時,右邊不再進行運算

Java 位元運算(移位、位與、或、異或、非)與邏輯運算

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.