Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between int and int received by ParseInt in java

Tags:

java

parseint

int i = 0;
int k = Integer.parseInt("12");
int j = k;
System.out.println(i+1 + " " + j+1);

Strangely the output received is

1 121

I can not figure out this basic difference. Please help me.

like image 728
Sachin Avatar asked Jun 13 '12 05:06

Sachin


2 Answers

Use brackets as follows

System.out.println((i+1) + " " + (j+1));

From the docs

The + operator is syntactically left-associative, no matter whether it is later determined by type analysis to represent string concatenation or addition. In some cases care is required to get the desired result. For example, the expression:

a + b + c is always regarded as meaning: (a + b) + c

Extending this to your scenario

i+1 + " " + j+1

it becomes

(((i + 1) + " ") + j)+1

Since i is an int so (i + 1) = 1 , simple addition

" " is a String hence ((i + 1) + " ") = 1 WITH SPACE (String concatenation)

Similarly when j and last 1 is added, its being added to a String hence String concatenation takes place, which justifies the output that you are getting.

See

  • JLS 15.18.1 String Concatenation Operator +
like image 117
jmj Avatar answered Sep 30 '22 07:09

jmj


that is beacuse of " ".

whenever a String comes, java doesnt do any calculations after that and just append it as string.

So in your case, i+1 is computed to 1, but " " + j+1 has string in it. So, it just appended together to form 121

like image 35
Kshitij Avatar answered Sep 30 '22 08:09

Kshitij