Store a number that is longer than type long in Java [duplicate]


How can I store a number that is longer than the long type (MAX: 9223372036854775807) in Java?

For example the number 9223372036854775820.

Thanks in advance.


Answers:


Use BigInteger if you work with a long and use BigDecimal if you work with floatingpoint numbers. The BigInteger can as big as you want, till there is not enough RAM.

Example:

    BigInteger bd = new BigInteger("922337203685477582012312321");
    System.out.println(bd.multiply(new BigInteger("15")));
    System.out.println(bd);

Output:

13835058055282163730184684815
922337203685477582012312321

But have to use the BigInteger methods to do calculations and in the example you see that BigInteger is immutable.