Why does this
int x = 2;
for (int y =2; y>0;y--){
System.out.println(x + \" \"+ y + \" \");
x++;
}
prints the s
This loop is the same as this while
loop:
int i = 0;
while(i < 5)
{
// LOOP
i++; // Or ++i
}
So yes, it has to be the same.
Because that statement is just on it's own. The order of the increment doesn't matter there.
Because the value of y
is calculated in for
statement and the value of x
is calculated in its own line, but in the System.out.println
they are only referenced.
If you decremented inside System.out.println
, you would get different result.
System.out.println(y--);
System.out.println(--y);
The increment is executed as an independent statement. So
y--;
and
--y;
are equivalent to each other, and both equivalent to
y = y - 1;
If the for
loop used the result of the expression i++
or ++i
for something, then it would be true, but that's not the case, it's there just because its side effect.
That's why you can also put a void
method there, not just a numeric expression.
Yes it does it sequentially. Intialisation, then evaluation condition and if true then executing the body and then incrementing.
Prefix and Postfix difference will be noticable only when you do an Assignment operation with the Increment/Decrement.