Pre -increment vs Post-increment
++i and i++ both increment the value of i by 1 but in a different way. If ++ precedes the variable, it is called pre-increment operator and it comes after a variable, it is called post-increment operator.
Increment in java is performed in two ways,
- Post-increment(i++)
- Pre-increment(++i)
Post-Increment (i++):
we use i++ in our statement if we want to use the current value, and then we want to increment the value of i by 1.
Example:
int i = 3;
int a = i++; // a = 3, i = 4
Pre-Increment(++i):
We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement.
Example:
int i = 3;
int b = ++a; // b = 4, a = 4
Many programming languages such as Java or C offer specialized unary operators for the pre-increment operations:(++operand) and (operand++). Both increment their argument variable by 1, but not the same way.
In particular, if x is an integer variable, and we pre-increment it as a part of a larger expression, the program will first add 1 to x and then evaluate x to the new value as the part of evaluation of the entire expression.
For example:
int x = 4;
int y = (++x) + 100;
//x = 5, y =
In contrast, the post-increment alternative will increment x but evaluate it to the old value inside the expression. Only after the expression has been evaluated does x have the new value:
int x = 4;
int y = (x++) + 100;
// x = 5, y = 104
As we can see, x = 5 in both cases, but the final value of y is different.