Converting a long variable to an int variable is a common task in Java programming.
In this tutorial, we will explore how to convert a long variable to an int variable in Java.
Firstly, it is important to understand the difference between a long and an int variable.
A long variable is a 64-bit signed two’s complement integer while an int variable is a 32-bit signed two’s complement integer.
The range of values that can be stored in a long variable is much larger than that of an int variable.
To convert a long variable to an int variable, we can simply cast the long variable to an int variable.
Here is an example:
long longValue = 123456789L; int intValue = (int) longValue;
In the above example, we have a long variable longValue
with the value 123456789L
.
We then cast this variable to an int variable intValue
using (int)
before the long variable name.
The resulting value of intValue
will be 7630401
.
It is important to note that if the value of the long variable is outside the range of the int variable, the resulting value of the int variable may not be what is expected.
For example:
long longValue = 2147483648L; int intValue = (int) longValue;
In the above example, the value of longValue
is outside the range of an int variable, which is -2147483648
to 2147483647
.
The resulting value of intValue
will be -2147483648
, which is the minimum value of an int variable.
In conclusion, converting a long variable to an int variable in Java is a simple task that can be accomplished by casting the long variable to an int variable.
However, it is important to be aware of the range of values that can be stored in each variable type to avoid unexpected results.