English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, we will learn how to convert a long variable to an integer (int) in Java.
To understand this example, you should understand the followingJava programmingTopic:
class Main { public static void main(String[] args) { //Create a long type variable long a = 2322331L; long b = 52341241L; //Convert long to int //Use type conversion int c = (int)a; int d = (int)b; System.out.println(c); // 2322331 System.out.println(d); // 52341241 } }
In the above example, we have long type variables a and b. Note the line,
int c = (int)a;
In this case, the higher data type long is converted to the lower data type int. Therefore, it is calledNarrowing type conversion). For more information, please visitJava Type Conversion.
When the value of the long variable is less than or equal to int(2147483647) works correctly. However, if the value of the long variable is greater than the maximum value of int, the data will be lost.
We can also use the toIntExact() method of the Math class to convert long values to int.
class Main { public static void main(String[] args) { //Create a long type variable long value1 = 52336L; long value2 = -445636L; //Convert long to int int num1 = Math.toIntExact(value1); int num2 = Math.toIntExact(value2); //Print the int value System.out.println(num1); // 52336 System.out.println(num2); // -445636 } }
Here, Math.toIntExact(value1) method converts the long variable value1Convert to int and return it.
If the returned int value is not within the range of the int data type, the toIntExact() method will throw an exception. As shown below,
//value exceeds the integer range long value = 32147483648L //throws an integer overflow exception int num = Math.toIntExact(value);
To learn more about the toIntExact() method, please visit Java Math.toIntExact().
In Java, we can also convert the object Long of the wrapper class to int. For this, we can use the intValue() method. For example,
class Main { public static void main(String[] args) { // Create an object of the Long class Long obj = 52341241L; //Convert Long object to int // Using the intValue() method int a = obj.intValue(); System.out.println(a); // 52341241 } }
Here, we create an object of the Long class named obj. Then, we use the intValue() method to convert the object to the int type.
For more information about wrapper classes, please visitJava Wrapper Classes.