The TwistyTie The TwistyTie - 9 months ago 24
Java Question

Dealing with numbers that are too large for int in Java

So I am trying to parse a string containing a number too large for Int storage. But I need the value of the string because I am dividing it. Can I parse the string into a Long?

n = Long.parseLong(string);

like that? Or is there a way I can divid the string by a number without having to turn the string into a number? The code I am using is like this:

private static String getFinished(String x, int y){
int word = Integer.parseInt(x);
word = word/y;

And the number I am using is: 1980715126555015951540148577071512651650
But I could potentially be using numbers even longer.


Can I parse the string into a Long?

Yes. Provided that the number isn't too big. The range for a long / Long is -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

Another alternative is to use BigInteger (javadoc). It can cope with numbers that are even larger. (The upper bound for BigInteger is most likely determined by the amount of memory you have available.)

The number I am using is: 1980715126555015951540148577071512651650

That requires a BigInteger. Example:

BigInteger small = new BigInteger("1980715126555015951540148577071512651650");
BigInteger notQuiteSoSmall = small.add(BigInteger.ONE);


  1. There is no operator overloading for BigInteger. You have to use explicit method calls.
  2. BigInteger objects are like String objects; i.e. they are immutable. Arithmetic methods produce a new BigInteger object.