Reputation: 107
I'm trying to convert this to a positive long but it is still printing as a negative. When I use other negative integers it works but not Integer.MIN_VALUE
if(num == Integer.MIN_VALUE){
long number = -num;
System.out.println(number);
}
Upvotes: 2
Views: 682
Reputation: 103018
long num = -num;
is executed as:
take the int num
, and negative it; it's still an int
. In other words, it remains Integer.MIN_VALUE
- because that's the one negative number amongst all 2^31 of em that doesn't have a positive equivalent, as 0
'takes up space' on the positive side of things.
Then, take the number we now have (still Integer.MIN_VAUE
, because -Integer.MIN_VALUE
is still Integer.MIN_VALUE
), and silently cast it to a long
, because that's a widening (safe) conversion, so java will just inject the cast for you.
The fix is to first cast to a long and then negative it:
either:
long number = num;
number = -number;
or in one go:
long number = -((long) num);
Upvotes: 1