2

Why does this code throw NumberFormatException?

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

How to get the value of int for that String?

Jason Coco
  • 77,985
  • 20
  • 184
  • 180
shree
  • 21
  • 1
  • 3
  • 5
    The `String` (viewed from the perspective as an `int`) exceeds `Integer.MAX_VALUE` (which is 2^31). – Josh M Sep 03 '13 at 17:25
  • See http://stackoverflow.com/questions/15717240/string-to-biginteger-java – fred02138 Sep 03 '13 at 17:26
  • That `String` is a not a valid `int`. – Sotirios Delimanolis Sep 03 '13 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). – Robert Harvey Sep 03 '13 at 17:26
  • There is no "value of int for that String". – SLaks Sep 03 '13 at 17:28
  • What @SLaks is saying in his usual terse way is that your string doesn't actually have an integer "value", although it could be a textual representation of some number, and could be parsed as such. Is it a binary number or decimal number you have there? – Robert Harvey Sep 03 '13 at 17:34

3 Answers3

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
2

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

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
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.

recursive
  • 83,943
  • 34
  • 151
  • 241