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?

1
  • Note that by specifying 16 as the second parameter to parseInt, you are parsing the string as a hexadecimal number. Commented Aug 19, 2010 at 8:03

5 Answers 5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

1 Comment

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.
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.

Comments

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).

Comments

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().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.