|
|
|
The above also apply for --var and var--.
(Except that that instead of incrementing the variable var by 1, the -- operators will decrement by 1)
Value in a | Operation |
Value in a after operation |
Returned value |
---|---|---|---|
4 | ++a | 5 | 5 |
4 | a++ | 5 | 4 |
4 | --a | 3 | 3 |
4 | a-- | 3 | 4 |
In other words:
|
public class Increment01 { public static void main(String[] args) { int a; a = 4; System.out.println(++a); // Prints 5 System.out.println(a); // Prints 5 a = 4; System.out.println(a++); // Prints 4 System.out.println(a); // Prints 5 a = 4; System.out.println(--a); // Prints 3 System.out.println(a); // Prints 3 a = 4; System.out.println(a--); // Prints 4 System.out.println(a); // Prints 3 } } |
How to run the program:
|
|
public class AssignExpr05 { public static void main(String[] args) { int a, b; a = 4; b = ++a + 1; // ++a evaluates to 5, so: 5 + 1 = 6 System.out.println(a); // Prints 5 System.out.println(b); // Prints 6 a = 4; b = a++ + 1; // a++ evaluates to 4, so: 4 + 1 = 5 System.out.println(a); // Prints 5 System.out.println(b); // Prints 5 } } |
Explanation:
b = ++a + 1; is evaluated as follows: b = ++a + 1; higher priority ^^^ ++a evaluates to 5 Reduces to: b = 5 + 1; = 6; |
How to run the program:
|
public class AssignExpr06 { public static void main(String[] args) { int a, b; a = 4; b = 2 * --a + 1; System.out.println(a); System.out.println(b); a = 4; b = 2 * (a-- + 1); System.out.println(a); System.out.println(b); } } |
Answer:
3 7 3 10 |
How to run the program:
|
a ++ -- or ++ -- a |
Because we don't encounter these constructs, I will omit the discussion of the associativity rules of the ++ and -- operators.