I am the following code:
for (int i = 0; i < 10;) {
i = i++;
System.out.println("Hola Mundo");
System.out.println("i = " + i); // Muestra i = 0
}
I don't understand why i
it is never equal to 1
.
I am the following code:
for (int i = 0; i < 10;) {
i = i++;
System.out.println("Hola Mundo");
System.out.println("i = " + i); // Muestra i = 0
}
I don't understand why i
it is never equal to 1
.
I reproduce the first iteration step by step:
1.-
for (int i = 0; i < 10;) {
At this point the value is assigned
0
toi
.two.-
i = i++;
At this point it
i
would increase its value by1
means of thei++
, but since it is a "postincrement" the value that is assigned toi
is the one it had before incrementing, the value is increased but the last thing that is executed is the assignment, keeping the value ofi
as I was.That last thing was not necessary, it could have remained as only
i++
, without the assignment.3.-
System.out.println("Hola Mundo");
Type "Hello World".
4.-
System.out.println("i = " + i); // Muestra i = 0
Here you write "i = 0" because
i
it has never been increased as you expected.If you want it to start with
1
you must correctly increase its value:To generalize, the operation:
always leave the original value. It doesn't just happen in Java, it's something that also happens in languages where the post- increment operation exists, like C, C++, C# or Javascript:
The reason is the way the statement is interpreted/executed: The postincrement to the variable is done after evaluating
i
, but BEFORE the assignment:i
lefti
on the right, which evaluates to0
.i
(the one on the left) has been evaluated, it is increasedi
by 1 (i
it is momentarily 1)i
:i = 0
The difference is that the postincrement returns the previous value of the variable, the main problem is that you reassign the value of the postincrement to the variable i, if you change
i = i++;
byi++;
o it wouldi = ++i;
solve the problem.Remember that programming is generally executed from right to left, so your logical para would be
i = i++
:As you can see your error is the assignment of
i = i++
, but if the variable were another functionary, it would bea
0 and in the next iteration 1 just like i would increase 1,2,3...10 anda
have the previous value 0,1,2 ...9:Questions like this often come up on Java certification exams.
In this link (in English) the Oracle documentation explains what is happening in your code. Considering that increment operator is ++ and decrement operator is --, let me quote this snippet
What translated would it be?
Applying this to your code
i = i++;
Bearing in mind that i is initially equal to 0, what it does is increase it by 1, but as the i++ documentation indicates, it evaluates to the original value 0 and that is the value that ends up being assigned, leaving the increase without effect.
If you change the site of the operator, you will see that the value of i increases
i = ++i;