34. Converting long into int

Converting a long value into an int value seems like an easy job. For example, a potential solution can rely on casting the following:

long nr = Integer.MAX_VALUE;
int intNrCast = (int) nr;

Alternatively, it can rely on Long.intValue(), as follows:

int intNrValue = Long.valueOf(nrLong).intValue();

Both approaches work just fine. Now, let's suppose we have the following long value:

long nrMaxLong = Long.MAX_VALUE;

This time, both approaches will return -1. In order to avoid such results, it is advisable to rely on JDK 8, that is, Math.toIntExact(). This method gets an argument of the long type and tries to convert it into int. If the obtained value overflows int, then this method will throw ArithmeticException:

// throws ArithmeticException
int intNrMaxExact = Math.toIntExact(nrMaxLong);

Behind the scenes, toIntExact() relies on the ((int)value != value) condition.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.195.225