1. 程式人生 > >Java 位運算(移位、位與、或、異或、非)與邏輯運算

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

高效率 邏輯與 才會 system 區別 span get 右移 邏輯

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 位運算(移位、位與、或、異或、非)與邏輯運算