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?
We can convert long to int in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Typecasting in java is performed through typecast operator (datatype).
Long is a larger data type than int, we need to explicitly perform typecasting for the conversion. Typecasting is performed through the typecast operator. There are basically three methods to convert long to int: By type-casting.
In Java when you cast you are changing the “shape” (or type) of the variable. The casting operators (int) and (double) are used right next to a number or variable to create a temporary value converted to a different data type. For example, (double) 1/3 will give a double result instead of an int one.
The cast rounds it "down" toward zero, while Math. floor rounds towards negative infinity.
The low 32 bits of the long
are taken and put into the int
.
Here's the math, though:
long
values as 2^64
plus that value. So -1
is treated as 2^64 - 1. (This is the unsigned 64-bit value, and it's how the value is actually represented in binary.)int
.)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With