I do not understand how {int a=10; a+=++a-5/3+6*a; System.out.print(a);} outputs 86

177 views Asked by At

I do not understand how

{
    int a = 10;
    a += ++a-5/3+6*a;
    System.out.print(a);
}

outputs 86

I know that shorthand notation has lower precedence than any of the operator used here so my thought process was to look it as

a = a + ++a-5/3+6*a

so if I apply precedence ++a increases value of a to 11 and then 5/3=1 and 6*11=66, so why does it not add the result of this expression (76) to 11 (incremented value of a)?

Right now what I understand is that the net of expression ++a-5/3+6*a which is 76 is added to old value of a that is 10. I do not understand why because when we evaluated the expression we did increment the a value but then how can i use the old value now?

1

There are 1 answers

5
sram21 On

The expression int a=10; a+=++a-5/3+6*a; System.out.print(a); is a combination of arithmetic operations and assignment. Let's break it down step by step to understand why it outputs 86:

int a=10;: This initializes the variable a with the value 10.

++a: This is a pre-increment operation, so it increments the value of a by 1, a becomes 11.

5/3: This is an integer division, which results in 1 (because it removes the fractional part).

6*a: This multiplies the current value of a (which is 11) by 6, resulting in 66.

Now, put above operations together:

++a results in a being 11. 5/3 results in 1. 6a results in 66. So, the expression ++a-5/3+6a evaluates to 11 - 1 + 66, which is equal to 76.

Now, let's go back to the original assignment:

a currently has the value 10. a += 76 is equivalent to a = a + 76, which updates the value of a to 86. Finally, System.out.print(a) prints the value of a, which is 86.