-7

For example:

 public static void main(String[] args)
{
String a="1";
int inc= Integer.parseInt(a+1);
System.out.println(inc);

 }

I'm getting 11 but i want to get 2. How can i do it in a very efficient way?

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
Nolimits
  • 43
  • 1
  • 3

2 Answers2

4

Integer.parseInt(a+1); parses the String that results from concatenating the value of the String a ("1") to the int literal 1, which is "11".

Change it to

int inc = Integer.parseInt(a) + 1;

This way "a" would be parsed to the integer 1 and then 1 would be added to it to give you the value 2.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Since a is a String object this operation is not giving the desired input

Integer.parseInt(a+1);

because will be equivalent to do

Integer.parseInt("1"+"1");

or

Integer.parseInt("11");

you need to parse the string first and then increment

 Integer.parseInt(a)+1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97