Languages
[Edit]
EN

Java - convert long to int

13 points
Created by:
Wallace
486

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.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join