How to Convert a Long to an Int in Java
Table of Contents
Java is a strongly-typed language which means that every variable has to have a type.
When it comes to numbers, you can represent them as int
, long
, float
, or double
.
Sometimes, you need to be able to convert a long
to an int
so that you can pass it into a method that only accepts an int
.
In this post, we'll learn how to convert a long
to an int
in Java.
How to convert a long to an int in Java
The issue with this conversion in general is that a long
contains more bits than an int
, this means it can contain a larger range of values.
If the long
contains a value larger than what an int
can hold, this can cause an overflow.
In any case, let's look at how to do this conversion.
The first way to do this is to simply cast the long
to an int
:
JAVAlong longValue = 10;
int intValue = (int) longValue;
If you want to be a bit safer doing this, you can add some simple checks:
JAVAlong longValue = 10;
int intValue;
if (longValue > (long) Integer.MAX_VALUE || longValue < (long) Integer.MIN_VALUE) {
throw new Exception("Value is too large");
} else {
intValue = (int) longValue;
}
If you want to use a built-in function, you can use the Math.toIntExact()
method:
JAVAlong longValue = 10;
int intValue = Math.toIntExact(longValue);
Just keep in mind that if the conversion fails, it will throw an exception.
Conclusion
In this post, we learned how to convert a long
to an int
in Java.
You can either attempt and directly cast the long
to an int
or you can use the Math.toIntExact()
method.
Thanks for reading!
- Getting Started with Express
- Create an RSS Reader in Node
- Getting Started with Electron
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API