DZone
With all the shiny things (lambda expressions, streams, Optional, the new Date/Time API, etc.) to distract my attention that came with JDK 8, I did not pay much attention to the addition of the method Math.toIntExact(). However, this small addition can be pretty useful in its own right.
The Javadoc documentation for Math.toIntExact(long) states, "Returns the value of the long
argument; throwing an exception if the value overflows an int
." This is particularly useful in situations where one is given or already has a Long
and needs to call an API that expects an int
. It’s best, of course, if the APIs could be changed to use the same datatype, but sometimes this is out of one’s control. When one needs to force a Long
into an int
there is potential for integer overflow because the numeric value of the Long
may have a greater magnitude than the int
can accurately represent.
Source: DZone