Why does Java's BigInteger have TEN and ONE as constants? Any Practical use? [closed]

Why does BigInteger class has constant TEN and ONE? Any practical uses for having them as constants? I can understand some use cases for ZERO.


Solution 1:

Let's say you have written a function that returns BigInteger after some calculations and db operations. You often may need to return values like null, 0, 1. It's easy to return BigInteger.ZERO. This values are public since they are needed commonly.

public BigInteger findMyLovelyBigInteger(Integer secretNumber) {
    if (secretNumber == null) {
        return BigInteger.ZERO; // better than BigInteger.valueOf(0);
    } else {
        // some db operations
    }
}

Also BigInteger.TEN is commonly used for power/divide/mod operations.

Checkout BigInteger public methods. You will easily see their common use cases.

Solution 2:

One is probably the most fundamental number in mathematics (alongside zero). Seems to deserve its own constant on that alone. Practically, it's a useful number to have as a constant in many algorithms.

Ten is important in the BigInteger context because it is the base of the decimal number system. This is important because several BigInteger functions need a radix base (e.g. BigInteger.toString(int radix). It's therefore a pretty useful constant to have.

Solution 3:

IMHO that was a design decision because 1 and 10 are used in other parts of the Java API code base. Creating Big* is an expensive operation and using constant avoid new object creation (Big* are immutable anyway) and the code is more readable.

Probably other constants weren't needed by the rest of the API.

Making them public was probably a fault. (The java API is full of "bad" design decisions)

Solution 4:

I don't know actually, but maybe:

  • zero: additive identity
  • one: multiplicative identity
  • ten: radix of the decimal system

Maybe they just used these constans a lot internally? (I haven't checked the source code, but it's Open Source).

Edit:

E.g.:

After looking at the code I think the reason is because they use ZERO and ONE a lot internally. Probably thought that others might profit from these constants as well given the reasons above. Or maybe they use these constants in some other classes as well.

TEN has been added in v1.5 It doesn't seem to be used internally, but maybe by another class?

http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/00cd9dc3c2b5/src/share/classes/java/math/BigInteger.java