Java Math toIntExact() Method

java math toIntExact() Method

Java Math Class

Java Math class provides several methods to perform several operations on math calculations like max(), min(), sin(), cos(), round(), ceil(), floor(), abs() etc.
The java.lang.Math class contains various methods for performing basic numeric operations

Here, in the page we will discuss about the math toIntExact() Method in java.

Java Math toIntExact() Method :

The Math.toIntExact(long value) method is a static method in the java.lang.Math class that converts a long value to an int value. It does this by checking if the value of the long can be represented as an int without loss of precision, and if so, it returns the int value. If the long value is too large to be represented as an int, the method throws an ArithmeticException.

Syntax  :

public static int toIntExact(long value)

Example 1 :  

Run
public class Main {
  public static void main(String[] args) {
    try {
      // Convert 100000L to int
      long longValue = 100000L;
      int intValue = Math.toIntExact(longValue);
      System.out.println(intValue); // Outputs: 100000

      // Convert 9999999999L to int
      longValue = 9999999999L;
      intValue = Math.toIntExact(longValue);
      // This line will not be reached because an ArithmeticException will be thrown
    } catch (ArithmeticException e) {
      System.out.println("Cannot convert 9999999999L to int because it is too large");
    }

    // Convert -100000L to int
    long longValue = -100000L;
    int intValue = Math.toIntExact(longValue);
    System.out.println(intValue); // Outputs: -100000
  }
}

Output :

100000
Cannot convert 9999999999L to int because it is too large
-100000

Example 2:  

Run
public class Main {
  public static void main(String[] args) {
    try {
      // Convert 9999999999L to int
      long longValue = 9999999999L;
      int intValue = Math.toIntExact(longValue);
      // This line will not be reached because an ArithmeticException will be thrown
    } catch (ArithmeticException e) {
      System.out.println("Cannot convert 9999999999L to int because it is too large");
    }
  }
}

Output :

Cannot convert 9999999999L to int because it is too large

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription