int overflow in java

Question:

There is a code

int a = Integer.MAX_VALUE;
int b = 5000;
int c = 123;
int min = Math.min(a, Math.min(b,c));
int max = Math.max(a, Math.max(b,c));
int d = a + b + c - min - max;

Why is the correct value stored in d ( b )?

After all, when we do a + b ( Integer.MAX_VALUE + 5000 ) we will have int'a overflow

Answer:

No, everything is correct. Together with overflows and it turns out.

Let's calculate step by step:

int step1 = a+b+c;
System.out.println(step1);
int step2 = step1-min;
System.out.println(step2);
int d = step2 - max;
System.out.println(d);

Output:

-2147478526
-2147478649
5000

It's just that at the last step, the second overflow -2147478649 -2147483647 and 5000 is obtained.

PS In general, the presence of overflow does not affect the associativity of the addition operation. In Java, addition of values ​​of the same integer type is always associative, as mentioned in the specification ( §JLS 15.18.2 ):

Integer addition is associative when the operands are all of the same type.

Accordingly, for any a and b , the value of a + b - b will be equal to a .

It follows from this that in your case d will always be equal to the average of the three numbers ( a , b and c ) regardless of their values.

Scroll to Top