Inspired by Actual Events: New BigInteger Methods in Java 8
Attention to new features in JDK 8 has rightfully been largely focused on new language features and syntax. However, there are some nice additions to the libraries and APIs and in this post I cover four new methods added to the BigInteger class: longValueExact(), intValueExact(), shortValueExact(), and byteValueExact().
All four of the newly introduced "xxxxxExact()" methods throw an ArithmeticException if the number contained in the BigInteger
instance cannot be provided in the specified form (specified in the method's name) without loss of information. BigInteger
already had methods intValue() and longValue() as well as inherited (from Number) methods shortValue() and byteValue(). These methods do not throw exceptions if the BigInteger
value loses information in the presentation as one of these types. Although at first glance this may seem like an advantage, it means that code that uses the results of these methods uses values that are not accurate without any ability to know that information was lost. The new "xxxxxExact" methods throw an ArithmenticException
rather than pretending to provide a result that has lost significant information.
The following simple code listing demonstrates the "legacy" methods that present wrong data in types byte
, short
, int
, and long
rather than throwing an exception. The same code also demonstrates use of the new "xxxxxExact" methods that throw an exception when information is lost rather than presenting a bad representation. The output of running this code follows the code and demonstrates how the methods behave differently when the BigInteger
contains a value with more information than the returned byte
, short
, int
, or long
can represent.
Read full article from Inspired by Actual Events: New BigInteger Methods in Java 8
No comments:
Post a Comment