ตัวดำเนินการ Java
ตัวดำเนินการ Java
ตัวดำเนินการใช้เพื่อดำเนินการกับตัวแปรและค่าต่างๆ
ในตัวอย่างด้านล่าง เราใช้ตัว
+
ดำเนินการเพื่อเพิ่มค่าสองค่าเข้าด้วยกัน:
ตัวอย่าง
int x = 100 + 50;
แม้ว่า+
โอเปอเรเตอร์มักจะใช้เพื่อเพิ่มค่าสองค่าเข้าด้วยกัน เช่นในตัวอย่างข้างต้น แต่ก็สามารถใช้เพื่อเพิ่มตัวแปรและค่าเข้าด้วยกัน หรือตัวแปรและตัวแปรอื่น ๆ ได้:
ตัวอย่าง
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
ตัวดำเนินการเปรียบเทียบใช้เพื่อเปรียบเทียบสองค่า:
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 Logical Operators
ตัวดำเนินการทางลอจิกใช้เพื่อกำหนดตรรกะระหว่างตัวแปรหรือค่าต่างๆ:
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) |