Difference between int and int received by ParseInt in java
Question by blunderboy
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.
Answer by Jigar Joshi
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
Answer by Starx
When you use " "
The expression after that gets evaluated as string.
Using brackets (
and )
around an expression can solve the problem in hand.
System.out.println(i+1 + " " + (j+1));