Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cannot parse "+1" to int? [duplicate]

Tags:

java

I am trying to parse +1 value to an int value. In my code +1 is a String and i am trying to convert it to Integer using Integer.parseInt,

String num = "+1";
int convertedNum = Integer.parseInt(num);

but I am getting error, why Java is not treating +1 as an integer value ?

like image 405
bhuvesh Avatar asked Dec 14 '22 16:12

bhuvesh


1 Answers

because you must be using older version of JDK (JDK < 7). Before Java 7, +1 wasn't considered as a valid integer.

Prior to JDK 1.7, what was the result of the following code segment?

double x = Double.parseDouble("+1.0");

int n = Integer.parseInt("+1");

Pat yourself on the back if you knew the answer: +1.0 has always been a valid floating-point number, but until Java 7, +1 was not a valid integer. This has now been fixed for all the various methods that construct int, long, short, byte, and BigInteger values from strings. There are more of them than you may think. In addition to parse (Int|Long|Short|Byte), there are decode methods that work with hexadecimal and octal inputs, and valueOf methods that yield wrapper objects. The BigInteger(String) constructor is also updated.

like image 91
Sufiyan Ghori Avatar answered Jan 03 '23 20:01

Sufiyan Ghori