ภาษา Java มี unary operator 2 ตัว สำหรับการเพิ่ม 1 หรือการลด 1 จากค่าปัจจุบันของตัวแปร (variable) มี unary increment operator, ++ และ unary decrement operator, -- เพื่อให้นักพัฒนาสามารถเขียนโค้ดได้สะดวกมากขึ้นแทนการเขียนแบบเต็ม
ยกตัวอย่างเช่น
c = c + 1;
สามารถใช้ unary operator เป็น
c++;
ตารางด้านล่างแสดงการใช้ unary operators ทั้งหมด
Operator |
Operator name |
Sample expression |
Explanation |
++ |
prefix increment |
++a |
เพิ่มขึ้น 1 แล้วนำค่าที่ได้ไปใช้ |
++ |
postfix increment |
a++ |
นำค่าไปใช้ก่อนแล้วค่อยเพิ่มขึ้น 1 |
-- |
prefix decrement |
--b |
ลดลง 1 แล้วนำค่าที่ได้ไปใช้ |
-- |
postfix decrement |
b-- |
นำค่าไปใช้ก่อนแล้วค่อยลดลง 1 |
ตัวอย่าง Source code แสดงผลการใช้ Increment และ Decrement Operators
public class Increment {
public static void main( String args[] ) {
int c;
c = 5; // assign 5 to c
System.out.println(c); // prints 5
System.out.println(c++); // prints 5 then postincrements
System.out.println(c); // prints 6
System.out.println();
c = 5;
System.out.println(c); // prints 5
System.out.println(++c); // preincrements then prints 6
System.out.println(c); // prints 6
} // end main
} // end class
Output
5
5
6
5
6
6
บทความถัดไป
สอน Java ตอนที่ 6.1 Control Statement แบบเงื่อนไข if