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
- Using toIntExact() method
- Using intValue() method of the Long wrapper class.
1. Using Explicit Type Casting
In typing casting, a data type is converted into another data type by the programmer using the casting operator during the program design. In typing casting, the destination data type may be smaller than the source data type when converting the data type to another data type, that’s why it is also called narrowing conversion.
destination_datatype = (target_datatype)variable; () is a casting operator.
target_datatype: is a data type in which we want to convert the source data type.
Type Casting Example:
float x; byte y; ... ... y=(byte)x;
Converted type: java.lang.Integer Converted int value is: 10000
2. Using toIntExact() method
public static int toIntExact(long value)
- value : the long value
This method returns the input argument as an int(integer).
It throws ArithmeticException – if the result overflows an int
Converted type: java.lang.Integer Converted type: java.lang.Integer 523386 -4456368
3. Using intValue() method of Long wrapper class
public int intValue()
Parameters: The method does not accept any parameters.
Return Value: The method returns the numeric value which is represented by the object after conversion to the integer type.
Converted type: java.lang.Integer Converted int value: 100
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.