Java演算子
Java演算子
演算子は、変数と値の操作を実行するために使用されます。
以下の例では、
+
演算子を使用して2つの値を加算します。
例
int x = 100 + 50;
演算子は、+
上記の例のように2つの値を加算するためによく使用されますが、変数と値、または変数と別の変数を加算するためにも使用できます。
例
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
Javaは、演算子を次のグループに分けます。
- 算術演算子
- 代入演算子
- 比較演算子
- 論理演算子
- ビット演算子
算術演算子
算術演算子は、一般的な数学演算を実行するために使用されます。
Operator | Name | Description | Example | Try it |
---|---|---|---|---|
+ | Addition | Adds together two values | x + y | |
- | Subtraction | Subtracts one value from another | x - y | |
* | Multiplication | Multiplies two values | x * y | |
/ | Division | Divides one value by another | x / y | |
% | Modulus | Returns the division remainder | x % y | |
++ | Increment | Increases the value of a variable by 1 | ++x | |
-- | Decrement | Decreases the value of a variable by 1 | --x |
Java代入演算子
代入演算子は、変数に値を代入するために使用されます。
以下の例では、代入演算子(=
)を使用して、値10をxと呼ばれる変数に代入します。
例
int x = 10;
代入演算子( )は+=
、変数に値を加算します。
例
int x = 10;
x += 5;
すべての代入演算子のリスト:
Operator | Example | Same As | Try it |
---|---|---|---|
= | x = 5 | x = 5 | |
+= | x += 3 | x = x + 3 | |
-= | x -= 3 | x = x - 3 | |
*= | x *= 3 | x = x * 3 | |
/= | x /= 3 | x = x / 3 | |
%= | x %= 3 | x = x % 3 | |
&= | x &= 3 | x = x & 3 | |
|= | x |= 3 | x = x | 3 | |
^= | x ^= 3 | x = x ^ 3 | |
>>= | x >>= 3 | x = x >> 3 | |
<<= | x <<= 3 | x = x << 3 |
Java比較演算子
比較演算子は、次の2つの値を比較するために使用されます。
Operator | Name | Example | Try it |
---|---|---|---|
== | Equal to | x == y | |
!= | Not equal | x != y | |
> | Greater than | x > y | |
< | Less than | x < y | |
>= | Greater than or equal to | x >= y | |
<= | Less than or equal to | x <= y |
Java論理演算子
論理演算子は、変数または値の間の論理を決定するために使用されます。
Operator | Name | Description | Example | Try it |
---|---|---|---|---|
&& | Logical and | Returns true if both statements are true | x < 5 && x < 10 | |
|| | Logical or | Returns true if one of the statements is true | x < 5 || x < 4 | |
! | Logical not | Reverse the result, returns false if the result is true | !(x < 5 && x < 10) |