Java Program to Convert long to int
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
import java.util.*;
class GFG {
public static void main(String[] args)
{
long longnum = 10000 ;
int intnum = ( int )longnum;
System.out.println( "Converted type: " + ((Object)intnum).getClass().getName());
System.out.println( "Converted int value is: "
+ intnum);
}
}
|
Output
Converted type: java.lang.Integer
Converted int value is: 10000
2. Using toIntExact() method
Syntax :
public static int toIntExact(long value)
Parameter:
Return:
This method returns the input argument as an int(integer).
Exception:
It throws ArithmeticException – if the result overflows an int
Java
class Main {
public static void main(String[] args) {
long value1 = 523386L;
long value2 = -4456368L;
int num1 = Math.toIntExact(value1);
int num2 = Math.toIntExact(value2);
System.out.println( "Converted type: " + ((Object)num1).getClass().getName());
System.out.println( "Converted type: " + ((Object)num2).getClass().getName());
System.out.println(num1);
System.out.println(num2);
}
}
|
Output
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
class GFG {
public static void main(String[] args)
{
Long longnum = 100L;
int intnum = longnum.intValue();
System.out.println( "Converted type: "
+ ((Object)intnum).getClass().getName());
System.out.println( "Converted int value: "
+ intnum);
}
}
|
Output
Converted type: java.lang.Integer
Converted int value: 100
Last Updated :
27 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...