I am using a large number -2147483648
in my program, and then if it is negative I have multiplied by -1
eg: -2147483648 * -1
Surprisingly I am not getting any positive numbers. So my entire code is not working because this value is large. But the java compiler will catch and say this is a large number, you can't use it here. Kotlin compiler will allow me to use this large number in my code.
why is this happening? Are my understandings wrong?
CodePudding user response:
The number 2,147,483,648 is larger than the largest Integer
which is 2,147,483,647.
Since Java does interpret all integer literals as int
, you do not get a positive result from multiplying -2147483648 * -1
due to an overflow.
Kotlin, on the other hand, does only interpret values up to 2,147,483,647 as Int
and above as Long
(see here). This is why the multiplication works in Kotlin without problems.
You can obtain the same result in Java by appending an L
to indicate that at least one of the numbers is a long
, or casting at least one of the parameters to long
, e.g. -2147483648L * -1
or -2147483648 * (long) -1
.
CodePudding user response:
To add to Karsten's answer, the reason it's not working in this specific case is because -2147483648
is interpreted by Kotlin as an Int
, since it's within the allowed range for ints (MIN_VALUE
specifically). But then you multiply it by -1
, which is another Int
, giving you an Int
result of 2147483648
That's one greater than MAX_VALUE
for Ints
, so it overflows back around to -2147483648
(MIN_VALUE
) and it looks like nothing happened, because your result is the same number you started with.
Basically your start value is interpreted as an Int
, but the result of this particular multiplication needs to be a Long
, so you either need to make your start value a Long
too, or multiply by -1L