Java中的算數運算子用於進行基本的數學運算,如加、減、乘、除等。以下是主要的算數運算子:
運算子包括:
範例程式碼:
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 10;
int b = 3;
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++;
System.out.println("a++ = " + a);
b--;
System.out.println("b-- = " + b);
}
}
比較運算子用於比較兩個值,返回布林值true
或false
。以下是主要的比較運算子:
運算子包括:
a == b
a != b
a > b
a < b
a >= b
a <= b
範例程式碼:
public class ComparisonOperators {
public static void main(String[] args) {
int a = 10;
int b = 20;
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));
}
}
賦值運算子用於將值賦給變數。以下是主要的賦值運算子:
運算子包括:
範例程式碼:
public class AssignmentOperators {
public static void main(String[] args) {
int a = 10;
int b = 5;
a += b;
System.out.println("a += b: " + a);
a -= b;
System.out.println("a -= b: " + a);
a *= b;
System.out.println("a *= b: " + a);
a /= b;
System.out.println("a /= b: " + a);
a %= b;
System.out.println("a %= b: " + a);
}
}
位元運算子用於對二進制位進行操作。以下是主要的位元運算子:
運算子包括:
範例程式碼:
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
System.out.println("a & b: " + (a & b)); // 0001 -> 1
System.out.println("a | b: " + (a | b)); // 0111 -> 7
System.out.println("a ^ b: " + (a ^ b)); // 0110 -> 6
System.out.println("~a: " + (~a)); // 1010 -> -6
System.out.println("a << 1: " + (a << 1)); // 1010 -> 10
System.out.println("a >> 1: " + (a >> 1)); // 0010 -> 2
System.out.println("a >>> 1: " + (a >>> 1)); // 0010 -> 2
}
}
運算子的優先等級決定了在沒有明確使用括號的情況下,運算子在表達式中被求值的順序。以下是一些常見運算子的優先等級,從高到低排列:
()
++
, --
, +
, -
, ~
, !
*
, /
, %
+
, -
<<
, >>
, >>>
<
, <=
, >
, >=
==
, !=
&
^
|
&&
||
? :
=
, +=
, -=
, *=
, /=
, %=
, &=
, |=
, ^=
, <<=
, >>=
, >>>=
範例程式碼:
public class OperatorPrecedence {
public static void main(String[] args) {
int a = 10;
int b = 5;
int c = 2;
// 優先級範例
int result = a + b * c; // 10 + (5 * 2) -> 10 + 10 -> 20
System.out.println("a + b * c = " + result);
result = (a + b) * c; // (10 + 5) * 2 -> 15 * 2 -> 30
System.out.println("(a + b) * c = " + result);
result = a / b * c; // (10 / 5) * 2 -> 2 * 2 -> 4
System.out.println("a / b * c = " + result);
result = a % b + c; // (10 % 5) + 2 -> 0 + 2 -> 2
System.out.println("a % b + c = " + result);
}
}