2

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.

MonsterJava
  • 423
  • 7
  • 23

3 Answers3

6

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
Maroun
  • 94,125
  • 30
  • 188
  • 241
1

Java compiler plays a little trick when it sees operator + applied to a String and a non-string: it null-checks the object, calls toString() on it, and then performs string concatenation.

That is what's happening when you write this:

query1 += "&" + PARAMETER  + "=" + count;
//        ^^^   ^^^^^^^^^    ^^^

You can certainly do this when the default conversion to String is what you want.

However, if you do this

String s = count; // <<== Error

the compiler is not going to compile this, because there is no concatenation. In this situation you would want to use valueOf:

String s = String.valueOf(count); // <<== Compiles fine
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

String.valueOf(int) actually calls Integer.toString().

So, it is used to convert an int to a String elegantly. As, doing i+"" is IMNSHO, not quite elegant.

Moreover, when you print any number directly, it actually calls the toString() method of its Wrapper class, and the prints the string.

dryairship
  • 6,022
  • 4
  • 28
  • 54