I have this silly question.
long val = Integer.MIN_VALUE * -1;
System.out.println(val);
Why does this print -2147483648.
A long should be able to accommodate the above product, right? Shouldn't the output be 2147483648
The product is computed as an int and then converted to long. But if one operand is long the result is the expected one.
Change -1 to -1L to compute as a long.
public static void main(String[] args) {
long val = Integer.MIN_VALUE * -1;
long longVal = Integer.MIN_VALUE * -1L;
System.out.println(Integer.MIN_VALUE);
System.out.println(val);
System.out.println(longVal);
}
The output is
-2147483648
-2147483648
2147483648
Integer.MIN_VALUE * -1;is still calculated asint, before it's assigned tolong. You need to either castInteger.MIN_VALUEtolongor multiply it with-1Linstead