English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java Math toIntExact() method usage and example

Java Math Mathematical Methods

The Java Math toIntExact() method returns an int value from the specified long parameter.

The syntax of the toIntExact() method is:

Math.toIntExact(long value)

Note: toIntExact() is a static method. Therefore, we can use the Math class name to access this method.

Parameter of toIntExact()

  • value - The parameter returned as int

Return value of toIntExact()

  • Return int value from the specified long value

Example1: Java Math.toIntExact()

class Main {
  public static void main(String[] args) {
    //Create long variable
    long value1 = 52336L;
    long value2 = -445636L;
    //Change long to int
    int num1 = Math.toIntExact(value1);
    int num2 = Math.toIntExact(value2);
    //Print int value
    System.out.println(num1);  // 52336
    System.out.println(num2);  // -445636
  }
}

In the above example, we used the Math.toIntExact() method to obtain an int value from the specified long variable.

Example2Math.toIntExact() throws an exception

If the returned int value is not within the range of the int data type, the toIntExact() method will throw an exception.

class Main {
  public static void main(String[] args) {
    //Create a long variable
    long value = 32147483648L;
    //Convert long to int
    int num = Math.toIntExact(value);
    System.out.println(num);
  }
}

In the above example, the value of the long variable is32147483648When we convert a long variable to an int, the resulting value exceeds the range of the int data type.

Therefore, the toIntExact() method triggers an integer overflow exception.

Recommended Tutorials

Java Math Mathematical Methods