Cannot convert String to Integer in Java [duplicate]
Asked Answered
N

5

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?

Nope answered 18/8, 2010 at 23:56 Comment(1)
Note that by specifying 16 as the second parameter to parseInt, you are parsing the string as a hexadecimal number.Metre
W
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);
Wanderlust answered 19/8, 2010 at 3:27 Comment(1)
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.Agro
R
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.

Reorientation answered 18/8, 2010 at 23:59 Comment(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.Agro
A
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.

Agro answered 18/8, 2010 at 23:59 Comment(0)
T
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).

Tomasatomasina answered 18/8, 2010 at 23:59 Comment(0)
E
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().

Erotic answered 19/8, 2010 at 0:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.