How to Convert Long to Int Type in Java

06 May 2023 Balmiki Mandal 0 Core Java

Converting Long to Int Type in Java

Java is a high-level language which offers a wide variety of data types, from primitives like integer and floating point numbers, to more complex data types like strings and classes. One such data type is called "long", which is used to represent large numbers that don't fit in the integer type. In some instances, you may need to convert a long value into an int type. Fortunately, this is quite easy to do in Java.

Using Math.toIntExact()

The easiest way to convert a long value to an int is by using the Math.toIntExact() method. This method takes a long as a parameter and returns an int if it fits. If the long cannot fit in an int, an ArithmeticException will be thrown.

For example, to convert the long 1234567890 to an int, you can use the following code:

long l = 1234567890;
int i = Math.toIntExact(l);
System.out.println(i); //prints 1234567890

Using Casting

If you don't want to use the Math.toIntExact() method, you can also cast a long value to an int. To do this, simply put the long in parentheses and add "int" before it. For example, to convert the long 1234567890 to an int, you can use the following code:

long l = 1234567890;
int i = (int) l;
System.out.println(i); //prints 1234567890

Using casting is slightly less reliable than using the Math.toIntExact() method, as it may throw an ArithmeticException if the long is too large to be represented as an int.

Conclusion

Converting a long value to an int is quite simple in Java. Using the Math.toIntExact() method or casting are both valid ways of doing so, with the former being more reliable in terms of avoiding exceptions.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.