How do the post increment (i++) and pre increment (++i) operators work in Java?
Does this help?
a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8)
a = 5;
i=a++ + ++a + ++a; =>
i=5 + 7 + 8; (a=8)
The main point is that ++a
increments the value and immediately returns it.
a++
also increments the value (in the background) but returns unchanged value of the variable - what looks like it is executed later.
Why is post increment operator in a return statement act different from expected in Eclipse?
Remember that the post increment operator evaluates to the original value before the increment is performed.
This means that e.g.
int a = i++;
is similar to doing:
int a = i;
i = i + 1;
That is, a
receives the original value of i
and after that, i
is incremented.
When used in a return statement, there's no difference, it evaluates to the value before the increment.
return _ix++ + giveMeZero();
would be similar to:
int temp = _ix;
_ix = _ix + 1;
return temp + giveMeZero();
In Java, how does a post increment operator act in a return statement?
The key part is that a post increment/decrement happens immediately after the expression is evaluated. Not only does it happen before the return occurs - it happens before any later expressions are evaluated. For instance, suppose you wrote:
class myCounter {
private int _ix = 1;
public int ixAdd()
{
return _ix++ + giveMeZero();
}
public int giveMeZero()
{
System.out.println(_ix);
return 0;
}
}
That would print out the incremented result as well, because the increment happens before giveMeZero()
is called.
Pre/Post increment operators and arrays
This:
int i= 0;
testArray[i++]= testArray[i++]+1;
is equivalent to:
int i= 0;
testArray[0]= testArray[1]+1;
which is equivalent to:
int i= 0;
testArray[0]= 20 + 1;
The post increment operator is increasing the value of the int
causing it to pull the element in index 1 in the expression, that index is ==
20. Obviously, the subsequent addition will make the value 21, which is then assigned to index 0 of the array.
To put it another way that relates to your description of the code. Your not using the index of the array that you assume you are.
Post increment operator not incrementing in for loop
for (int i = 0; i < 10; i = i++) {
The above loop is essentially the same as: -
for (int i = 0; i < 10; i = i) {
the 3rd part of your for
statement - i = i++
, is evaluated as: -
int oldValue = i;
i = i + 1;
i = oldValue; // 3rd Step
You need to remove the assignment from there, to make it work: -
for (int i = 0; i < 10; i++) {
(On OP request from Comments)
Behaviour of x = 1; x = x++ + x++;
: -
As far as your issue as specified in the comment is concerned, the result of the following expression: -
x = 1;
x = x++ + x++;
is obtained as follows: -
Let's mark different parts of the second statement: -
x = x++ + x++;
R A B
Now, first the RHS part (A + B)
will be evaluated, and then the final result will be assignmed to x
. So, let's move ahead.
First A
is evaluated: -
old1 = x; // `old1 becomes 1`
x = x + 1; // Increment `x`. `x becomes 2`
//x = old1; // This will not be done. As the value has not been assigned back yet.
Now, since the assignment of A
to R
is not done here, the 3rd step is not performed.
Now, move to B
evaluation: -
old2 = x; // old2 becomes 2. (Since `x` is 2, from the evaluation of `A`)
x = x + 1; // increment `x`. `x becomes 3`.
// x = old2; // This will again not be done here.
Now, to get the value of x++ + x++
, we need to do the last assignment that we left in the evaluation of A
and B
, because now is the value being assigned in x
. For that, we need to replace: -
A --> old1
B --> old2 // The last assignment of both the evaluation. (A and B)
/** See Break up `x = old1;` towards the end, to understand how it's equivalent to `A = old1; in case of `x = x++`, considering `x++ <==> A` in this case. **/
So, x = x++ + x++
, becomes: -
x = old1 + old2;
= 1 + 2;
= 3; // Hence the answer
Break up of 3rd part of x = x++
, to see how it works in x = x++ + x++
case: -
Wonder why the replacement is done as A --> old1
and not x --> old1
, as in case of x = x++
.
Take a deep look at x = x++
part, specially the last assignment: -
x = oldValue;
if you consider x++
to be A
here, then the above assignment can be broken into these steps: -
A = oldValue;
x = A;
Now, for the current problem, it is same as: -
A = old1;
B = old2;
x = A + B;
I hope that makes it clear.
When to use post increment and pre increment in Java
PRE-increment is used when you want to use the incremented value of the variable in that expression., whereas POST-increment uses the original value before incrementing it.
Whenever your code encounters a PRE-increment, it increments the value of that variable in the memory, then load that value and continues reading the expression.
POST-increment does the opposite, it loads that value of that variable in the memory, then increments the value and continues reading the expression.
To make it more clear, consider this
int i = counter++;
is equivalent to
int i = counter;
counter = counter + 1;
WHEREAS
int i = ++counter;
is equivalent to
counter = counter + 1;
int i = counter;
EDIT: My StackOverflow comments arent working, so I'll just edit it here.
What I'm saying it, it only matters when you use that value in an expression.
sum = 0
counter = 0;
sum = (++counter)+(++counter)+(counter++)
evaluates as
sum = 0
counter = 0
//For first ++counter
counter = counter + 1
sum = counter
//For second ++counter
counter = counter + 1
sum = sum + counter
//For first counter++
sum = sum + counter
counter = counter + 1
Java increment and assignment operator
No, the printout of 10 is correct. The key to understanding the reason behind the result is the difference between pre-increment ++x
and post-increment x++
compound assignments. When you use pre-increment, the value of the expression is taken after performing the increment. When you use post-increment, though, the value of the expression is taken before incrementing, and stored for later use, after the result of incrementing is written back into the variable.
Here is the sequence of events that leads to what you see:
x
is assigned10
- Because of
++
in post-increment position, the current value ofx
(i.e.10
) is stored for later use - New value of
11
is stored intox
- The temporary value of
10
is stored back intox
, writing right over11
that has been stored there.
Confusion with increment operators in Java in conditional statements
In the first case you're comparing 10 (not yet incremented) to 11 (already post-incremented when evaluating first i++)
In the second case you're comparing 21 (pre incremented) to 21 (post-incremented by earlier evaluation)
Your thinking was good, however you're not factoring what happens with second i/j in the equals condition
post-increment, pre-increment. JAVA
EDITED
Here are the steps to evaluate the expression:
- Evaluate all the expression that has increment/decrement from left to right
- Replace all variable with their true value
- Evaluate the expression using PEMDAS rule
Example:
int x = 4;
int y = ++x * 5 / x-- + --x;
first we need to substitute all values of
x
before evaluating the expression (substitute from left to right)++x
-> since it is a post increment we will first incrementx
before substituting, thusx
will be 55 * 5 / x-- + --x
-> this will be the new equation
now we will substitutex
inx--
x--
-> since it is a post decrementx
here will be substituted with 5 and after the substitution decrementx
, thusx
will be 45 * 5 / 5 + --x
-> this will be the new equation
now we will substitutex
in--x
--x
-> since it is a pre decrement we will first decrementx
substituting, thusx
will be 35 * 5 / 5 + 3
// this will be the new equationSince there are no variables in the equation we will now evaluate the expression using PEMDAS
25 / 5 + 3
5 + 3
8
thus the result will be 8
Related Topics
How to Get Active User's Userdetails
Differencebetween Join and Join Fetch When Using JPA and Hibernate
The Performance Impact of Using Instanceof in Java
Using Pairs or 2-Tuples in Java
Useful Example of a Shutdown Hook in Java
How Good Is Java's Uuid.Randomuuid
Java Random Numbers Using a Seed
Difference Between Java Hh:Mm and Hh:Mm on Simpledateformat
When Is the @JSONproperty Property Used and What Is It Used For
How to Compare Two Dates Without the Time Portion
Inject an Ejb into Jax-Rs (Restful Service)
Concurrentmodificationexception Despite Using Synchronized
How to Put Axis on a .Png File in Java
Any Way to Invoke a Private Method
Differencebetween Method Overloading and Overriding
Java:If a Extends B and B Extends Object, Is That Multiple Inheritance
Multiple Line Code Example in Javadoc Comment
What Does the Question Mark in Java Generics' Type Parameter Mean