Search code examples
javamathoperation

Tricky basic java operations


I got these 2 different codes in Java that I can't understand how they produce these specific outputs.

They seemed to work in 2 different logic and I can't figure it out!

int a = 5;
int b = 4;
a -= (b++) + ++a; // For more confusing results replace -= with += and see how the logic changes.
System.out.println(a); // Output: -5

and

int c = 8;
c += ++c;
System.out.println(++c); // Output: 18

How does each situation work and how are they producing these specific outputs?


Solution

  • The major difference here is what post and pre increment are. These determine whether the value is increased before evaluation, or afterward.

    Here is how the first case breaks down mathematically:

    a = 5 - (4 + 6), which reduces to -5.

    Note that a is increased from ++a AKA preincrement before the math is done, however b is calculated as 4. Another thing to note is the a used from the -= uses the original a value, regardless of post or pre increment.

    The second equation reduces to this mathematically:

    c = 8 + 9 which reduces to 17.

    The output prints 18 because your System.out.print(++c) increments it one more time before output due it being preincrement. Note if the print statement used c++, the value would print to 17.

    The chart for operator precedence can be found here. Note that assignment has lower precedence than the unary/postfix operators.