Problems
1. Operators
Why both print same values?
for (i = 0;i<10;i++) {
System.out.print(i);
}
System.out.println();
for (i=0;i<10;++i) {
System.out.print(i);
}
// 0123456789
// 0123456789
Both i++
and ++i
increment the value of i
by 1, but the difference lies in when the increment happens in expressions — not in loops like for
where the value isn't used during increment.
i++
→ Post-increment: Incrementsi
after the value is used++i
→ Pre-increment: Incrementsi
before the value is used
But in a for
loop:
for (i = 0; i < 10; i++) // or ++i
The increment expression (i++
or ++i
) happens after each iteration, and its return value is not used anywhere in the loop control itself.
So both loops behave the same:
Initialize
i = 0
Check condition
i < 10
Execute
System.out.print(i)
Increment
i
(post or pre — doesn’t matter because value isn't used)Repeat
If we wrote something like:
int x = i++;
int y = ++i;
Here, the difference matters:
x = i++
: assigns the value ofi
tox
, then incrementsi
y = ++i
: incrementsi
, then assigns the new value toy
Last updated
Was this helpful?