Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

math
java
communitycreator

What is Math.toIntExact() in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The toIntExact method takes a single long argument and returns the int value of the passed value. The toIntExact method is a static method present in the Math class.

Syntax

public static int toIntExact(long a);

Argument

  • a: The long value to be converted to int.

Return value

This method returns the int value of the long argument.

The toIntExact method is equivalent to:

long value to int value

Example

import java.lang.Math;
class ToIntExactTest {
public static void main(String cmdArgs[]) {
long a = 1000l;
int intA = Math.toIntExact(a);
System.out.print("The int value of "+ a + " is ");
System.out.println(intA);
long b = -1234l;
int intB = Math.toIntExact(a);
System.out.print("The int value of "+ b + " is ");
System.out.println(intB);
}
}

In the code above:

  • We created two variables, a and b, of the long type.

  • We called toIntExact with a as an argument. This will return an equivalent int value of a. We did the same for variable b.


The toIntExact method will throw ArithmeticException if the long value overflows the int value.

Example

For example, the ArithmeticException will be thrown if the value of the argument is lesser than the minimum value or greater than the maximum value that the int type can hold.

import java.lang.Math;
class ToIntExactTest {
public static void main(String cmdArgs[]) {
try{
long a = 33333333333l;
int intVal = Math.toIntExact(a);
}catch(Exception e) {
System.out.println(e);
}
}
}

In the code above, we created a variable, a, of the long type. We assigned the 33333333333l value to the a variable.

When we call the toIntExact method with a as an argument, we will get ArithmeticException because the 33333333333l value is greater than the value an integer can hold.

RELATED TAGS

math
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring