1. 程式人生 > 資訊 >京東小哥上門服務:熱水器/空調/洗衣機清洗 74 元好價(立減 50 元)

京東小哥上門服務:熱水器/空調/洗衣機清洗 74 元好價(立減 50 元)

運算子

Java語言支援的運算子

  • 算術運算子:+、-、*、/、%、++、--
  • 賦值運算子:=
  • 關係運算符:>、<、>=、<=、==、!=、instanceof
  • 邏輯運算子:&&、||、!
  • 位運算子:&、|、^、>>、<<、>>>
  • 條件運算子:? :
  • 擴充套件賦值運算子:+=、-=、*=、/=

自增自減運算子

一元運算子 ++、--

public class Demo03 {
    public static void main(String[] args) {
        int a = 3;
        int b = a++;//a++ a = a+1;執行完這行程式碼後,先給b賦值,再自增
        System.out.println(a);
        int c = ++a;//++a  a = a+1;執行完這行程式碼前,先自增,再給c賦值

        System.out.println(a);
        System.out.println(b);
        System.out.println(b);
        System.out.println(c);
        System.out.println(c);

    }
}

Math類

 double s = Math.pow(2,8);
        System.out.println((int)s);

得到結果 256

邏輯運算子

public class Demo04 {
    public static void main(String[] args) {
        //與或非 and/or/取反
        boolean a = true;
        boolean b = false;
        System.out.println("a&&b:"+(a&&b));
        System.out.println("a||b:"+(a||b));
        System.out.println("!(a&&b):"+!(a&&b));
    }
}

位運算

public class Demo05 {
    public static void main(String[] args) {
        /**
         * A = 0011 1100
         * B = 0000 1101
         *
         * A&B = 0000 1100  交
         * A|B = 0011 1101  並
         * A^B = 0011 0001 異或
         * ~B = 1111 0010  取反
         *
         * 2*8=16  2*2*2*2
         *<<左移 *2
         *>>右移 /2
         * 0000 0000      0
         * 0000 0001      1
         * 0000 0010      2
         * 0000 0011      3
         * 0000 0100      4
         * 0000 0101      5
         * 0000 0110      6
         * 0000 0111      7
         * 0000 1000      8
         * 0001 0000      16
         */
        System.out.println(2<<3);
    }
}
  • 位運算優點:效率高

三元運算子

public class Demo07 {
    public static void main(String[] args) {
        //x ? y : z
        //如果x==true,則結果為y,否則結果為z
        int score = 80;
        String type = score < 60 ?"不及格":"及格";
        System.out.println(type);
    }
}

結果為:及格

+=、-=、*=、/=

public class Demo06 {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        a+=b;
        System.out.println(a);

        //字串連線符 +,String
        System.out.println(""+a+b);
        
        System.out.println(a+b+"");
    }
}