Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safely casting long to int in Java

Tags:

java

casting

What's the most idiomatic way in Java to verify that a cast from long to int does not lose any information?

This is my current implementation:

public static int safeLongToInt(long l) {     int i = (int)l;     if ((long)i != l) {         throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");     }     return i; } 
like image 605
Brigham Avatar asked Oct 19 '09 20:10

Brigham


People also ask

Can you cast a long to an int in Java?

You can cast a long to int so long as the number is less than 2147483647 without an error.

How do I cast a long number in Java?

Java int can be converted to long in two simple ways:Using a simple assignment. This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types. Using valueOf() method of the Long wrapper class in java which converts int to long.

Can you cast a String to an int in Java?

In Java, we can use Integer. valueOf() and Integer. parseInt() to convert a string to an integer.

What should we concern when casting in Java?

One of the foremost concerns related to casting in Java refers directly to the two type groups in Java. The two types of groups are primitive and reference. The first attention of this discourse would go to the casting of primitives to ensure type conversion.


1 Answers

A new method has been added with Java 8 to do just that.

import static java.lang.Math.toIntExact;  long foo = 10L; int bar = toIntExact(foo); 

Will throw an ArithmeticException in case of overflow.

See: Math.toIntExact(long)

Several other overflow safe methods have been added to Java 8. They end with exact.

Examples:

  • Math.incrementExact(long)
  • Math.subtractExact(long, long)
  • Math.decrementExact(long)
  • Math.negateExact(long),
  • Math.subtractExact(int, int)
like image 134
Pierre-Antoine Avatar answered Sep 22 '22 18:09

Pierre-Antoine