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.
Syntax/Declaration:
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;
// Java Program to convert long to int import java.util.*;
class GFG {
public static void main(String[] args)
{
// long value
long longnum = 10000 ;
// explicit type casting from long to int
int intnum = ( int )longnum;
System.out.println( "Converted type: " + ((Object)intnum).getClass().getName());
System.out.println( "Converted int value is: "
+ intnum);
}
} |
Converted type: java.lang.Integer Converted int value is: 10000
2. Using toIntExact() method
Syntax :
public static int toIntExact(long value)
Parameter:
- value : the long value
Return:
This method returns the input argument as an int(integer).
Exception:
It throws ArithmeticException – if the result overflows an int
// Java Program to convert long to int class Main {
public static void main(String[] args) {
// create long variable
long value1 = 523386L;
long value2 = -4456368L;
// change long to int
int num1 = Math.toIntExact(value1);
int num2 = Math.toIntExact(value2);
// print the type
System.out.println( "Converted type: " + ((Object)num1).getClass().getName());
System.out.println( "Converted type: " + ((Object)num2).getClass().getName());
// print the int value
System.out.println(num1); // 52336
System.out.println(num2); // -445636
}
} |
Converted type: java.lang.Integer Converted type: java.lang.Integer 523386 -4456368
3. Using intValue() method of Long wrapper class
Syntax:
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.
// Java Program to convert long to int using intValue() // method class GFG {
public static void main(String[] args)
{
// Long object
Long longnum = 100L;
// Converting Long object to int primitive type
int intnum = longnum.intValue();
// printing the type
System.out.println( "Converted type: "
+ ((Object)intnum).getClass().getName());
// printing the int value
System.out.println( "Converted int value: "
+ intnum);
}
} |
Converted type: java.lang.Integer Converted int value: 100