Search code examples
javaparseint

Difference between int and int received by ParseInt in java


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.


Solution

  • 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