How to store a large (10 digits) integer?

Viewed 153735

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

9 Answers

Your concrete example could be stored in long (or java.lang.Long if this is necessary).

If at any point you need bigger numbers, you can try java.math.BigInteger (if integer), or java.math.BigDecimal (if decimal)

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

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

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

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.

If you want to take user input then you should take that as string, then convert that into long.

//Take user input using Scanner class

Scanner sc = new Scanner(System.in);
String str = sc.next();

//Convert that to long

long num = Long.parseLong(str);

System.out.println(num); // This is not a string anymore
Related