Java – Why does Java define BigInteger / BigDecimal values of 10

javamath

Question perhaps slightly left of field – but I'm curious as to the logic behind why Java's BigInteger/BigDecimal classes feel the need to define a constant of TEN?

Example taken from java.math.BigInteger:

/**
 * The BigInteger constant zero.
 *
 * @since   1.2
 */
public static final BigInteger ZERO = new BigInteger(new int[0], 0);

/**
 * The BigInteger constant one.
 *
 * @since   1.2
 */
public static final BigInteger ONE = valueOf(1);

/**
 * The BigInteger constant two.  (Not exported.)
 */
private static final BigInteger TWO = valueOf(2);

/**
 * The BigInteger constant ten.
 *
 * @since   1.5
 */
public static final BigInteger TEN = valueOf(10);

Now I'm assuming it might be something to do with use in scaling functions or the like, but it did make me curious – especially since TEN seems to first appear in 1.5 whereas ONE and ZERO existed much earlier (I can also see why 1 and 0 would be more immediately useful than 10, too)

Anyone know?

Best Answer

BigInteger and BigDecimal are immutable objects. Once instantiated, if you want to do something with it, you create a new object. This isn't a problem per say, and actually avoids many other problems (especially when threading), and numbers tend to be things that are constants - you don't change them.

It is very common for code that is working with BigDecimal and BigInteger to need to use the values 0, 1, 2, and 10. If these were not defined as constants in the class, programmers would often find themselves instantiating those objects again and again. This can be a problem because it means you are creating objects unnecessarily where there are perfectly acceptable and commonly used objects.

I once worked on a code base where miles and kilometers were frequently used. Prior to a clean up, we had over a dozen different places where there was a static BigDecimal MILES_IN_ONE_KM = new BigDecimal("0.621371") in one way, shape, form or another - fortunalty there were only those and they were statics rather than being created every time we converted from one distance unit to another...

This is a rather special case of the Object Pool Pattern. Other examples of it can be found in the Integer cache (primary used in boxing / unboxing), and the Color class where things such as 'RED' and 'BLUE' are defined.

By allocating these commonly used objects in the class, it provides a rather low cost to have a few extra objects floating around rather than creating and destroying scores every time you want to multiply a number by 10 or add 1.

Related Topic