Search code examples
javastringcastingvalue-of

Difference between String.valueOf(int i) and printing only i


See the below code snippet:

int count = 0;
String query = "getQuery"; 
String query1 = "getQuery";
final String PARAMETER = "param";

query += "&" + PARAMETER  + "=" + String.valueOf(count);
query1 += "&" + PARAMETER  + "=" + count;
System.out.println("Cast to String=>"+query);
System.out.println("Without casting=>"+query1);

Got the both output exactly same. So I am wondering why this has been used when we can get the same result by using only count.

I got some link but did not found exactly same confusion.


Solution

  • This is well explained in the JLS - 15.18.1. String Concatenation Operator +:

    If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

    You should note the following:

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

    If you write 1 + 2 + " fiddlers" the result will be

    3 fiddlers
    

    However, writing "fiddlers " + 1 + 2 yields:

    fiddlers 12