Issue
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);
}
Solution
long num = -num;
is executed as:
take the int
num
, and negative it; it's still anint
. In other words, it remainsInteger.MIN_VALUE
- because that's the one negative number amongst all 2^31 of em that doesn't have a positive equivalent, as0
'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 stillInteger.MIN_VALUE
), and silently cast it to along
, 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);
Answered By - rzwitserloot