[java] How to store a large (10 digits) integer?

Which Java data type would be able to store a big numerical value, like 9999999999?

This question is related to java

The answer is


you can use long or double.


A wrapper class java.lang.Long can store 10 digit easily.

   Long phoneNumber = 1234567890;

It can store more than that also.

Documentation:

public final class Long extends Number implements Comparable<Long> {
    /**
     * A constant holding the minimum value a {@code long} can
     * have, -2<sup>63</sup>.
     */
    @Native public static final long MIN_VALUE = 0x8000000000000000L;

    /**
     * A constant holding the maximum value a {@code long} can
     * have, 2<sup>63</sup>-1.
     */
    @Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
}

This means it can store values of range 9,223,372,036,854,775,807 to -9,223,372,036,854,775,808.


Use BigInt datatype with its implicit operations. The plus point for it is it will not give answers in exponential representation. It will give full length result

Here is an example of addition

      BigInteger big1 = new BigInteger("1234567856656567242177779");
      BigInteger big2 = new BigInteger("12345565678566567131275737372777569");
      BigInteger bigSum = big1.add(big2);
      System.out.println(bigSum );

In addition to all the other answers I'd like to note that if you want to write that number as a literal in your Java code, you'll need to append a L or l to tell the compiler that it's a long constant:

long l1 = 9999999999;  // this won't compile
long l2 = 9999999999L; // this will work

A primitive long or its java.lang.Long wrapper can also store ten digits.


You could store by creating an object that hold a string value number to store in an array list. by example: BigInt objt = new BigInt("999999999999999999999999999999999999999999999999999");

objt is created by the constructor of BigInt class. Inside the class look like.

BigInt{

ArrayList<Integer> myNumber = new ArrayList <Integer>();        

public BigInt(){}

public BigInt(String number){ for(int i; i<number.length; i++){ myNumber.add(number.indexOf(i)); } }

}

You can store this in a long. A long can store a value from -9223372036854775808 to 9223372036854775807.