EN
Java - convert long to int
13 points
In java we can convert long to int by:
- using typecasting eg: (int) longValue
- Math.toIntExact
- Long.intValue
xxxxxxxxxx
1
long val = 1000L;
2
int intVal = (int) val;
3
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.
xxxxxxxxxx
1
long val = 1000L;
2
int intVal = Math.toIntExact(val);
3
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
.
xxxxxxxxxx
1
Long val = 1000L;
2
int intVal = val.intValue();
3
System.out.println(intVal); // 1000
Long
class have intValue()
method which allow us to perform typecasting.