1. 程式人生 > 其它 >第五話-運算子

第五話-運算子

運算子總結

程式碼demo

package operator;

public class Demo01 {
    public static void main(String[] args) {
        //二元運算子
        //Ctrl + d : 複製當前行到下一行
        int a = 10;
        int b = 20;
        int c = 25;
        int d = 25;
        System.out.println(a+b);
        System.out.println(a-b);
        System.out.println(a*b);
        System.out.println(a/(double)b);

        //運算子計算後型別轉換
        long a1 = 123123123123L;
        int b1 = 123;
        short c1 = 10;
        byte d1 = 8;
        System.out.println(a1+b1+c1+d1); //Long
        System.out.println(b1+c1+d1);    //Int
        System.out.println(c1+d1);       //Int

        //關係運算符返回的結果: 正確,錯誤 布林值
        int a2 = 10;
        int b2 = 20;
        int c2 = 21;
        System.out.println(c2%b2);
        System.out.println(a2>b2);
        System.out.println(a2<b2);
        System.out.println(a2==b2);
        System.out.println(a2!=b2);

        //++自增 --自減 一元運算子
        int aa = 3;
        int bb = aa++;
        int cc = ++aa;
        System.out.println(aa);
        System.out.println(bb);
        System.out.println(cc);

        //Math工具類,冪運算,2^3=8,還支援很多數學函式
        double pow = Math.pow(2, 3);
        System.out.println(pow);

        //邏輯運算子,與 或 非
        boolean booa = true;
        boolean boob = false;
        System.out.println("booa&&boob:"+(booa&&boob));  //false,兩個都為真,則結果true
        System.out.println("booa||boob:"+(booa||boob));  //true,有一個為真,則結果true
        System.out.println("!(booa&&boob)"+!(booa&&boob));//true

        //短路運算:與運算,第一個為false,則無需繼續執行,第二個c++沒有執行。
        int booc = 5;
        boolean bood = (c<5)&&(c++<5);
        System.out.println(bood + "," + booc);

        //位運算
        /*
        A   = 0011 1100
        B   = 0000 1101
        ------
        A&B = 0000 1100 //兩個都為1則結果是1
        A|B = 0011 1101 //有一個為1則結果是1
        A^B = 0011 0001 //相同為0,不同為1
        ~B  = 1111 0010 //取反

        <<  *2   效率高
        >>  /2
        0000 0010  2
        0000 0100  4
        0000 1000  8
        0001 0000  16
         */
        System.out.println(2<<3); //2 (*2)三次

        //擴充套件賦值運算子:+=,-=,*=,/=
        int aaa = 10;
        int bbb = 20;
        aaa+=bbb; //aaa = aaa + bbb
        System.out.println(aaa+","+bbb);

        //字串連線符 +
        System.out.println(aaa+bbb+"");
        System.out.println(""+aaa+bbb);

        //三元運算子: x ? y : z
        // 如果x==true,則結果為y,否則結果為z
        int score = 50;
        String type = score<60 ? "不及格" : "及格";
        System.out.println(type);

    }
}