Java Math toIntExact(long value) Method

The java.lang.Math.toIntExact() is a built-in math function in java which returns the value of the long argument.It throws an exception if the result overflows an int.As toIntExact(long value) is static, so object creation is not
required.

Syntax :

public static int toIntExact(long value)
Parameter :
value : the long value
Return :
This method returns the input argument as an int(integer) .
Exception :
It throws ArithmeticException - if the result overflows an int

Example :To show working of java.lang.Math.toIntExact() method.



filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate working
// of java.lang.Math.toIntExact() method
import java.lang.Math;
  
class Gfg1 {
    // driver code
    public static void main(String args[])
    {
        long a = 499;
        System.out.println(Math.toIntExact(a));
    }
}

chevron_right


Output:

499
filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate working
// of java.lang.Math.toIntExact() method
import java.lang.Math;
  
class Gfg2 {
  
    // driver code
    public static void main(String args[])
    {
        long x = Long.MAX_VALUE;
  
        System.out.println(Math.toIntExact(x));
    }
}

chevron_right


Output:

Runtime Error :
Exception in thread "main" java.lang.ArithmeticException: integer overflow
    at java.lang.Math.toIntExact(Math.java:1011)
    at Gfg2.main(File.java:12)


My Personal Notes arrow_drop_up

Welcome to Wenzkaba Planet

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.