This question is not about how a long should be correctly cast to an int, but rather what happens when we incorrectly cast it to an int.
So consider this code –
@Test
public void longTest()
{
long longNumber = Long.MAX_VALUE;
int intNumber = (int)longNumber; // potentially unsafe cast.
System.out.println("longNumber = "+longNumber);
System.out.println("intNumber = "+intNumber);
}
This gives the output –
longNumber = 9223372036854775807
intNumber = -1
Now suppose I make the following change-
long longNumber = Long.MAX_VALUE - 50;
I then get the output –
longNumber = 9223372036854775757
intNumber = -51
The question is, how is the long’s value being converted to an int?
The low 32 bits of the
longare taken and put into theint.Here’s the math, though:
longvalues as2^64plus that value. So-1is treated as 2^64 – 1. (This is the unsigned 64-bit value, and it’s how the value is actually represented in binary.)int.)