There is a code ( updated ):
int s = 0; for (int i = 0; i < 10; i++) { s = s + s++; } System.out.println(s); Actually the question is why s after the cycle will be equal to 0 ?
There is a code ( updated ):
int s = 0; for (int i = 0; i < 10; i++) { s = s + s++; } System.out.println(s); Actually the question is why s after the cycle will be equal to 0 ?
Because the assignment s = works after the increase in s ++ works out.
In steps:
If you used ++ s, everything would be different. In step 2, ++ s would return 1, as expected. True, the "s = ++ s" construct would be no different from "++ s" or "s ++", except for an extra write operation in memory.
UPD c taking into account the change in listing, as yozh said, the explanation remains valid
there is an expression s = s + s ++
s++ returns the old value. But the assignment of a new value to the variable s occurs during the increment itself. - yozhThe variable s will increase by one only after the execution of the TOTAL block, if it is necessary for it to increase the value BEFORE the execution of the block, you must write ++s .
I reworked your code a bit, I'm just starting to work with java myself, but I think the problem is that 0 is not incremented (I do not claim it).
class One { public static void main(String[] args) { int s = 1; for(int i = 0; i<10; i++) { s = s + s++; System.out.println(s); // тут s = 0; (уже после отработки цикла) } } } If you give s a value of 1, then we get
2 4 8 16 32 64 128 256 512 1024 In my opinion, this is what was required. in the first line the value is 2, which means that when outputting to System.out.println (); the increment has not yet occurred, otherwise there would be 3.
(}) closed, but after System.out.println(s); which java and considers the end of the block. - arachnoden a = ++i // сначала i увеличивается на 1, потом присваивается к а b = i++ // сначала i присваивается к b, потом увеличивается на 1 Different compilers may handle these operations in different ways, so it is advised not to abuse such constructs. A good article is on the habr about the construction i = i++ + ++i;
Source: https://ru.stackoverflow.com/questions/43736/
All Articles