0

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

1
  • 3
    Yes, but Integer.MIN_VALUE * -1; is still calculated as int, before it's assigned to long. You need to either cast Integer.MIN_VALUE to long or multiply it with -1L instead Commented Jul 24, 2021 at 22:00

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

I got that part, else the answer would be +ve. So is every multiplication of whole numbers treated as an int unless explicitly specified?
Got it, that is what I was looking for, thank you! I should've clarified in my question, based on the error I get what is happening but wanted to understand the correct behavior!
re So is every multiplication of whole numbers treated as an int unless explicitly specified? No. (1) LIterals are int unless suffixed by L, which makes them long. (2) Arithmetic on int values gives an int result. (3) Arithmetic operations where one operand is int and the other long will first widen the int to long.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.