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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With