To be clear the following is perfectly legal Java:
String fruit = ...;
int n = ...;
String newString = x + fruit;
The diadic +
operator is String concatenation if either the left or right operand expression's type is String
; see JLS 15.18.
The following is equivalent in this case:
String newString = "" + x + fruit;
The initial ""
is a common idiom that makes it crystal clear to the reader that string concatenation is involved. (I personally wouldn't use it though, since it looks clunky to me. IMO, it is like adding redundant parentheses to help programmers who don't know the operator Java precedence rules. Icck.)
In the example above, the ""
makes no semantic difference. However, there are occasions where the leading ""
changes the meaning of the expression. For example:
int x = 1;
String fruit = " bananas";
String newString = x + x + fruit; // "2 bananas"
String newString2 = "" + x + x + fruit; // "11 bananas".
(Note that the javac
compiler is permitted by the JLS to aggressively optimize a sequence of String concatenations, so the apparent concatenation with ""
will be optimized away.)