Home > Java > javaTutorial > body text

How Can You Safely Cast a Long to an Int in Java?

DDD
Release: 2024-10-26 14:59:31
Original
538 people have browsed it

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>
Copy after login

Other Overflow-Safe Methods:

In addition to toIntExact, Java 8 also added several other overflow-safe methods that end with "exact." These methods include:

  • Math.incrementExact(long)
  • Math.subtractExact(long, long)
  • Math.decrementExact(long)
  • Math.negateExact(long)
  • Math.subtractExact(int, int)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!