2

Why does this code throw NumberFormatException?

int a = Integer.parseInt("1111111111111111111111111111111111111111");

How to get the value of int for that String?

6
  • 5
    The String (viewed from the perspective as an int) exceeds Integer.MAX_VALUE (which is 2^31). Commented Sep 3, 2013 at 17:25
  • See stackoverflow.com/questions/15717240/string-to-biginteger-java Commented Sep 3, 2013 at 17:26
  • That String is a not a valid int. Commented Sep 3, 2013 at 17:26
  • 1
    int has a maximum value of 2,147,483,647. Are you trying to parse a binary representation instead? If you are, you've got 40 bits there, so it still won't fit (int only stores 32). Commented Sep 3, 2013 at 17:26
  • There is no "value of int for that String". Commented Sep 3, 2013 at 17:28

3 Answers 3

12

The value that you're attempting to parse is much bigger than the biggest allowable int value (Integer.MAX_VALUE, or 2147483647), so a NumberFormatException is thrown. It is bigger than the biggest allowable long also (Long.MAX_VALUE, or 9223372036854775807L), so you'll need a BigInteger to store that value.

BigInteger veryBig = new BigInteger("1111111111111111111111111111111111111111");

From BigInteger Javadocs:

Immutable arbitrary-precision integers.

Sign up to request clarification or add additional context in comments.

Comments

2

This is because the number string is pretty large for an int . Probably this requires a BigInteger .

Comments

1

There is no integer value for that string. That's why it's throwing an exception. The maximum value for an integer is 2147483647, and your value clearly exceeds that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.