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.

4
  • Why are you expecting a different output? Commented Apr 11, 2016 at 12:54
  • 1
    Understand that when you concatenate a String literal and an int (or any primitive type), the int (or primitive) is automatically converted to a String. Commented Apr 11, 2016 at 12:54
  • I am not expecting any different output but want to know the reason why this has been used. (If any of cource) Commented Apr 11, 2016 at 12:56
  • 1
    It's used when you don't concatenate a primitive with a String literal. Commented Apr 11, 2016 at 12:57

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

That's what I'm looking for -- a reference to the JLS. Thanks. 1+
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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.