【JAVA】運算子表示式
阿新 • • 發佈:2022-05-09
算術運算
+ - * / %(取餘) ++ (自增) -- (自減)
public class MathCalcu{ public static void main(String[] args){ int a = 10; int b = 2; int jiafa = a + b; System.out.println("a + b = " + jiafa); int jianfa = a - b; System.out.println("a - b = " + jianfa);int chengfa = a * b; System.out.println("a * b = " + chengfa); int chufa = a / b; System.out.println("a / b = " + chufa); int quyu = a % b; System.out.println("a % b = " + quyu); } }
編譯結果:
i++ // 先賦值後加1
++i // 先加1後賦值
public class MathCalcu{public static void main(String[] args){ int a = 10; int b = 2; // 字尾自增自減法(a++,a--): 先進行表示式運算,再進行自增或者自減運算 System.out.println("a = " + (a)); System.out.println("a++ = " + (a++)); System.out.println("a = " + (a)); System.out.println("a-- = " + (a--)); System.out.println("a = " + (a)); System.out.println("======================="); // 字首自增自減法(++b,--b): 先進行自增或者自減運算,再進行表示式運算 System.out.println("b = " + (b)); System.out.println("++b = " + (++b)); System.out.println("--b = " + (--b)); System.out.println("b = " + (b)); } }
編譯結果:
關係運算
> < >= <= == != 【得到的結果是一個布林型別】
public class MathCalcu{ public static void main(String[] paramArrayOfString) { byte b1 = 3; byte b2 = 4; boolean bool = (b1 > b2) ? true : false; System.out.println("result = " + bool); bool = (b1 <= b2) ? true : false; System.out.println("result = " + bool); System.out.println("3 == 4 --> false"); System.out.println("3 != 4 --> true"); } }
編譯結果:
位運算: 二進位制運算 0 1
A = 0011 1100 = 60
B = 0000 1101 = 13
public class MathCalcu{ public static void main(String[] paramArrayOfString) { byte b1 = 4; //0000 0100 System.out.println(b1 ^ 0xFFFFFFFF); // 異或 byte b2 = 6; //0000 0110 System.out.println(b1 & b2); System.out.println(b1 | b2); System.out.println(b1 ^ b2); System.out.println(b2 << 2); System.out.println(b2 >>> 2); } }
編譯結果:
邏輯運算
&& : 邏輯與(短路與)
true && true = true;
true && false = false;
false && true = false;
false && false = false;
|| : 邏輯或
true || true = true;
true || false = true;
false || true = true;
false || false = false;
! : 邏輯非
!true = false;
!false = true;
public class MathCalcu{ public static void main(String[] args) { 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)); } }
編譯結果:
賦值運算
條件運算(三目運算)
布林型別表示式?值1:值2;
為真,結果為值1;
為假,結果為值2;
public class MathCalcu{ public static void main(String[] args) { int a = 2; int b = 3; int c = a > b ? a : b; boolean d = a > b ; System.out.println("表示式結果為:" + d); System.out.println("c = " + c); } }
編譯結果:
運算子優先順序排序