This content has been marked as final. Show 5 replies
Why do you need a reason? it doesn't work. If the original developer of the code behind valueOf() would drop in and explain to you exactly why (which will likely be in the area of "oops"), that still doesn't change a thing: you can't do it.
Of course you could dig a little deeper and know that valueOf actually uses parseInt() so it is in fact parseInt() which does not like parsing numbers which start with a '+' sign. But still, you aren't going to get anywhere looking for a reason. You'd better focus on searching for an alternative way of dealing with it.
maybe that's why the compiler is complaining.Nobody said anything about a compiler complaining.
Well, there could be different reasons for using "+1" instead of just "1"; for instance, the need to read/parse data, like temperature, produced by a third party application. It's not a problem to just ignore '+' sign when reading the data, but it still does not answer the question.
Edited by: user13471201 on Jun 5, 2012 8:45 AM
Edited by: user13471201 on Jun 5, 2012 8:46 AM
Welcome to the forum!
The Integer.valueOf(String) works fine with strings like "-1", but does not work with "+1". The following code throws NumberFormatException:
int i = Integer.valueOf( "+1" );
Does anybody know what's the reason for this?
The short answer is because it is defined that way.
The place to start for questions like this is the Javadoc.
You don't state what Java version you are using but for 1.6 the 'valueOf' method says this
public static Integer valueOf(String s)
throws NumberFormatExceptionReturns an Integer object holding the value of the specified String. The argument is interpreted as representing a signed decimal integer, exactly as if the argument were given to the parseInt(java.lang.String) method. The result is an Integer object that represents the integer value specified by the string.
As you can see the description further refers you to the 'parseInt' method where you will find the answer.
public static int parseInt(String s)
throws NumberFormatExceptionParses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
You may have to do a little digging but when you have a question like this you should read the relevant Javadoc sections, search the forum for similar questions, search on the net and then if you still can't figure it out post a thread.