Java移位元運算符和賦值運算子__Java編程經驗

來源:互聯網
上載者:User
一.移位元運算符 移位元運算符也針對二進位的“位”,它主要包括:左移位元運算符(<<)、右移位元運算符(>>>)、帶符號的右移位元運算符(>>)。其中: 左移運算子用“<<”表示,是將運算子左邊的對象,向左移動運算子右邊指定的位元,並且在低位補零。其實,向左移 n 位,就相當於乘上 2 的 n 次方。 右移運算子用符號“>>>”表示,是將運算子左邊的對象向右移動運算子右邊指定的位元,並且在高位補 0,其實右移 n 位,就相當於除上 2 的 n 次方。 帶符號的右移運算子用符號“>>”表示,是將運算子左邊的運算對象,向右移動運算子右邊指定的位元。如果是正數,在高位補零,如果是負數,則在高位補 1。
public class data17{
    public static void main(String[] args){
        int a=2;    int b=2;
        int x=16;    int y=2;
        int m=16;    int n=2;    int p=-16;    int q=2;

        System.out.println("a 移位的結果是:"+(a<<b));
        System.out.println("x 移位的結果是:"+(x>>>y));
        System.out.println("m 的移位結果:"+(m>>n));
        System.out.println("p 的移位結果:"+(p>>q));
    }
}

運行結果:
a 移位的結果是:8
x 移位的結果是:4
m 的移位結果:4
p 的移位結果:-4 二.賦值運算子 賦值就是將數值賦給變數,而這個賦值運算子就充當了這個賦值的任務,其實最簡單的賦值運算子,就是“=”。

當然除了“=”外,還有很多其他的賦值運算子。有“+=”、“-=”、“*=”、“/=”、“%=”、“>>=”、“>>>=”、“<<=”、“&=”、“|=”、“^=”。下面有一個簡單的例子。

public class data20{
    public static void main(String[] args){
        int a=5;
        int b=2;
        System.out.println("a+=b 的值:"+(a+=b));
       System.out.println("a-=b 的值:"+(a-=b));
       System.out.println("a*=b 的值:"+(a*=b));
       System.out.println("a/=b 的值:"+(a/=b));
       System.out.println("a%=b 的值:"+(a%=b));
       System.out.println("a>>=b 的值:"+(a>>=b));
       System.out.println("a>>>=b 的值:"+(a>>>=b));
       System.out.println("a<<=b 的值:"+(a<<=b));
       System.out.println("a&=b 的值:"+(a&=b));
       System.out.println("a|=b 的值:"+(a|=b));
       System.out.println("a^=b 的值:"+(a^=b));
    }
}

輸出結果:
“a+=b”就是 a=a+b=7;
“a-=b”就是 a=a-b=7-2=5;
“a*=b”就是 a=a*b=5*2=10;
“a/=b”就是 a=a/b=10/2=5;
“a%=b”就是 a=a%b=5%2=1;
“a>>=b”就是 a=a>>b=0;
“a>>>=b”就是 a=a>>>b=0;
“a<<=b”就是 a=a<<b=0;
“a&=b”就是 a=a&b=0;
“a|=b”就是 a=a|b=2;
“a^=b”就是 a=a^b=0;

聯繫我們

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