Integer.parseInt ("9999999990");

I am getting NumberFormatException for line 9999999990, but not when I use 1111111110 when I call Integer.parseInt on this Line. Let me know what is wrong.

String str="9999999990";
  int f = Integer.parseInt("2147483647");// No Exception here
        int x =Integer.parseInt(str);   // Exception is thrown here 



source to share

2 answers


will throw an exception if its parse cannot be represented as int

. The first example is almost 10 billion, which is more than the maximum possible int

, which is just over 2 billion.


delegates Integer.parseInt(String, 10)

, the version that takes the root, and the state of the Javadocs:

A NumberFormatException is thrown when one of the following situations occurs:

  • The first argument is null or a zero-length string.
  • The radius is either less than Character.MIN_RADIX or greater than Character.MAX_RADIX.
  • Any character in the string is not a digit of the specified radius, except that the first character can be a minus sign '-' ('\ u002D') or plus sign '+' ('\ u002B'), provided that the string is longer than length 1.
  • The value represented by the string is not an int .

(emphasis mine)

If you need it, you can use Long.parseLong

one that will handle large numbers.



An int

can only have a maximum value of 2147483647, so if you try to parse a number greater than that, you will get an exception (since it is not valid int



will handle large numbers, but remember that it still has an upper limit (2 ^ 63-1). If you really want a type with no upper limit, you will need to use BigInteger

(which has a constructor that takes a string).

(More information on all primitive data types and their maximum values ​​can be found ).



All Articles