Search code examples
javaincrementoperator-keyword

java and Arithmetic Operators and Increment


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.


Solution

  • The rule to remember is: Think from left to right.

    int a = 2;
    int b = 4;
    a = b++; // First assign b to a, then increment b.
    // Here a=4, b=5
    a = ++b; // Cannot set a to ++. First increment b, then assing the incremented value to a.
    // Here a=6, b=6