Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How negating a value is same as the value in java [Integer.Min_Value]

How can these values be same in java?

-Integer.MIN_VALUE == Integer.MIN_VALUE

values are:

-2147483648 : -2147483648

i tried comparing it and returns true [Amazing!]

like image 254
Dineshkumar Avatar asked May 18 '26 02:05

Dineshkumar


1 Answers

Yes, that's expected behaviour. The range of int is -2147483648 to +2147483647.

From the JLS section 15.15.4 (emphasis mine):

For integer values, negation is the same as subtraction from zero. The Java programming language uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values x, -x equals (~x)+1.

~Integer.MIN_VALUE is Integer.MAX_VALUE... and when you add one, it overlows to Integer.MIN_VALUE.

This is why when you implement a reversing comparator, you mustn't do this:

// BAD CODE!
public int compare(T x, T y) {
    return -originalComparator.compare(x, y);
}

Instead, use this:

// This is fine, assuming the comparator obeys its contract
public int compare(T x, T y) {
    return originalComparator.compare(y, x));
}
like image 191
Jon Skeet Avatar answered May 19 '26 15:05

Jon Skeet