It is one of the simple operations and I do not understand why and I just save it, but this bothers me, so I want to understand why?
int a = 2;
int b = 4;
int c = 10;
a = b++;
System.out.println(a);
a = ++b;
System.out.println(a);
This process ++ I did not understand how it works. In this case, the output is 4 and 6
But I only added 1 and the result was an added 2
In the beginning, she only took the value 4 without added any thing, then in the second output, she added 2
If you put the code in the sixth line a = ++c, the output will be by adding 1, not 2, to c.
so Some help to understand please.
On the other hand, since = is an assignment, I imagine that the result will preserve the last number, and now if I modify the code as follows:
int a = 2;
int b = 4;
int c = 10;
a = b++;
System.out.println(a);
a = ++c;
System.out.println(a);
a = ++b;
System.out.println(a);
Here the output will be
4
11
6
I did not expect this either, as the last output should have been 5, not 6.
So I would like some help, please, so that I can understand and not just memorize.
a = b++;, it adds 1 tob, but it copies the OLD value intoa. Thus,awill be 4, butbwill be5. When you doa = ++b;, it bumpsbby 1 BEFORE it does the copy.bbecomes 6, so that's what is stored ina. The original value ofais never used. Your second example bumpsbTWICE. It becomes 6.a = b++;->a = b; b = b + 1;, whereasa = ++b;->b = b + 1; a = b;.a = b++are two operations: 1)b++, a post-increment operation that results in the value before the increment was done; 2)a = <result from b++>, an assignment that stores the result of previous point ina|| difference betweenb++and++b: the first one results in the value before incrementing; the second results in the value after incrementing (bwill always be incremented) || Also note thata = b; b = b + 1;is not always the correct replacement: the assignment is done after the incrementing