EN
Java - convert long to int
13
points
Overview
In java we can convert long to int by:
- using typecasting eg: (int) longValue
- Math.toIntExact
- Long.intValue
1. Using typecasting
long val = 1000L;
int intVal = (int) val;
System.out.println(intVal); // 1000
Type casting - when we assign value of one primitive data type to another type.
In this case from long to int.
2. Math.toIntExact
long val = 1000L;
int intVal = Math.toIntExact(val);
System.out.println(intVal); // 1000
Java 8 added method toIntExact
to Math
class.
If the passing long value overflows an int it will throw ArithmeticException
.
3. Long.intValue
Long val = 1000L;
int intVal = val.intValue();
System.out.println(intVal); // 1000
Long
class have intValue()
method which allow us to perform typecasting.