16

I have written a function to convert string to integer

   if ( data != null )
   {
        int theValue = Integer.parseInt( data.trim(), 16 );
        return theValue;
   }
   else
       return null;

I have a string which is 6042076399 and it gave me errors:

Exception in thread "main" java.lang.NumberFormatException: For input string: "6042076399"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:461)

Is this not the correct way to convert string to integer?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Ding
  • 163
  • 1
  • 1
  • 4
  • Note that by specifying 16 as the second parameter to `parseInt`, you are parsing the string as a hexadecimal number. – Jesper Aug 19 '10 at 08:03

5 Answers5

14

Here's the way I prefer to do it:

Edit (08/04/2015):

As noted in the comment below, this is actually better done like this:

String numStr = "123";
int num = Integer.parseInt(numStr);
Steve Pierce
  • 322
  • 2
  • 9
  • Unless things have changed, `Integer.parseInt()` is the preferred method as it will cache commonly used values to improve performance. Creating a new Integer will always create a new Integer object. However, this was pre-Java 5 - I wouldn't be surprised if both do the same thing now. – Thomas Owens Aug 19 '10 at 15:26
9

An Integer can't hold that value. 6042076399 (413424640921 in decimal) is greater than 2147483647, the maximum an integer can hold.

Try using Long.parseLong.

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • 1
    He's using primitive types. I would recommend a `long` before a `Long`. I would also possibly even recommend a `BigInteger` before a `Long`, although I'm not entirely sure about that. – Thomas Owens Aug 19 '10 at 00:04
4

That's the correct method, but your value is larger than the maximum size of an int.

The maximum size an int can hold is 231 - 1, or 2,147,483,647. Your value is 6,042,076,399. You should look at storing it as a long if you want a primitive type. The maximum value of a long is significantly larger - 263 - 1. Another option might be BigInteger.

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
2

That string is greater than Integer.MAX_VALUE. You can't parse something that is out of range of integers. (they go up to 2^31-1, I believe).

codersarepeople
  • 1,971
  • 3
  • 20
  • 25
1

In addition to what the others answered, if you have a string of more than 8 hexadecimal digits (but up to 16 hexadecimal digits), you could convert it to a long using Long.parseLong() instead of to an int using Integer.parseInt().

Frank
  • 2,628
  • 15
  • 14