LAST UPDATED: DECEMBER 1, 2020
How to convert Java long to int
In Java, a long
can be converted into an int
using the typecast operator. This is because, in order to convert a higher data type into a lower data type, typecasting needs to be performed and this type of conversion is called Typecasting conversion.
In Java, Typecasting is performed through the typecast operator (datatype).
Example 1:
Here, the primitive long
value is converted into int
using the typecasting operator.
public class StudyTonight
{
public static void main(String args[])
{
long l = 500L;
int i = (int)l; //typecasting
System.out.println("The int value is " +i);
}
}
The int value is 500
Also, we can convert a Long object to an int by intValue() method of Long class.
Example 2:
Here, the Long
object is converted into int by using the intValue() method.
public class StudyTonight
{
public static void main(String args[])
{
Long l = new Long(50);
int i = l.intValue();
System.out.println("The int value is : " +i);
}
}
The int value is : 50
Example 3:
Here, the primitive long
value is converted into int
using toIntExact()
method of the Math
class.
public class StudyTonight
{
public static void main(String args[])
{
long l = 100L;
int i = Math.toIntExact(l);
System.out.println("The int value is " +i);
}
}
The int value is 100