Safely Converting to Integer with toIntExact() Method in Java: A Complete Guide

Rumman Ansari   Software Engineer   2024-07-04 04:29:52   6080  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

Description

In this tutorial we will be showing a java example on how to use the toIntExact(long value) method of Math Class. The toIntExact(long value) returns the value of the long argument; throwing an exception if the value overflows an int. 

Most of the methods of the Math class is static and the toIntExact() method is no exception. Thus don’t forget that in order to call this method, you don’t have to create a new object. Use the method in the format Math.toIntExact(value).

From the first part we have described this method to throw an exception if the result overflows the specified data type. If you are interested on the limit of the result before it throws an exception, you can find it using Integer.MIN_VALUE and Integer.MAX_VALUE.

With the complicated description above on this method functionality, you might start to wonder why not directly convert from long to int. That might be the easiest solution though if we breach the limitation of data type the result would be inconsistent which probably would happen because long can handle higher values than int, not unlike if we use the toIntExact() which has the capability to throw an exception if the result overflows of its range. So with this capability to throws an exception, will give us room to provide mechanism to handle such scenario.

Notes:

  • ArithmeticException will be throw if the result of the operation overflows int.

Method Syntax

public static int toIntExact(long value)

Method Returns

The toIntExact() method returns the argument as an int.

Compatibility

Requires Java 1.8 and up

Example

Below is a java code demonstrates the use of toIntExact() method of Math class. The example presented might be simple however it shows the behaviour of the toIntExact() method.



import java.util.Scanner;

/*
 * This example source code demonstrates the use of
 * toIntExact() method of Math class
 */

public class MathToIntExact {

	public static void main(String[] args) {

		// initialize long variables
		long value1 = 123l;
		long value2 = 3147483647l;


		// direct conversion from long to int
		int intVal1 = (int) value1;
		int intVal2 = (int) value2;

		// print the result
		System.out.println("Direct conversion val1:"+intVal1);
		System.out.println("Direct conversion val2:"+intVal2);


		// use Math.toIntExact()
		try{
			intVal1 = Math.toIntExact(value1);
			System.out.println("Using toIntExact val1:"+intVal1);
		}catch(ArithmeticException e){
			System.out.println("value1 overflows an int");
		}

		try{
			intVal2 = Math.toIntExact(value2);
			System.out.println("Using toIntExact val2:"+intVal2);
		}catch(ArithmeticException e){
			System.out.println("value2 overflows an int");
		}


	}

}

output

Below is the sample output when you run the above example.

Direct conversion val1:123
Direct conversion val2:-1147483649
Using toIntExact val1:123
value2 overflows an int
Press any key to continue . . .

The above java example source code demonstrates the use of toIntExact() method of Math class. There are two values initially declared value1 and value2. The first value certainly is within range of the int however the second one is more that the maximum value as defined by Integer.MAX_VALUE. So at first part we have used casting to convert the long to int values and as expected the result would be wrong on the conversion of the second value.

The second part is we have converted the values into int using the Math.toIntExact and we have also used try-catch in order to handle the exception when in such case that values intended to be converted to int is not within range. This example shows on how we can leverage the exception that can be thrown when the conversion is not proper.