June 13, 2012

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));

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!