Home >Java >javaTutorial >How Can You Safely Cast a Long to an Int in Java?
Casting Long to Int Safely in Java
Casting a long to an int can potentially result in information loss. To prevent this, it's essential to verify that the cast does not alter the value.
Traditional Approach:
One common approach involves casting to an int and then casting back to a long to check for equality. However, this method has a limitation: it fails for values larger than 2^31-1.
Java 8 Solution:
Java 8 introduced a more robust solution: Math.toIntExact(long). This method throws an ArithmeticException if the cast results in overflow.
<code class="java">long foo = 10L; int bar = Math.toIntExact(foo); // Throws ArithmeticException on overflow</code>
Other Overflow-Safe Methods:
In addition to toIntExact, Java 8 also added several other overflow-safe methods that end with "exact." These methods include:
Using these methods ensures the integrity of your data and prevents unexpected integer overflows.
The above is the detailed content of How Can You Safely Cast a Long to an Int in Java?. For more information, please follow other related articles on the PHP Chinese website!