The \\+
symbol can mean three distinct operators in Java:
\\+
, then it is the unary Plus operator.String
, then it it the binary Concatenation operator.In the simple case, the Concatenation operator joins two strings to give a third string. For example:
String s1 = "a String";
String s2 = "This is " + s1; // s2 contains "This is a String"
When one of the two operands is not a string, it is converted to a String
as follows:
toString()
on the boxed value.toString()
method. If the operand is null
, or if the toString()
method returns null
, then the string literal "null"
is used instead.For example:
int one = 1;
String s3 = "One is " + one; // s3 contains "One is 1"
String s4 = null + " is null"; // s4 contains "null is null"
String s5 = "{1} is " + new int[]{1}; // s5 contains something like
// "{} is [I@xxxxxxxx"
The explanation for the s5
example is that the toString()
method on array types is inherited from java.lang.Object
, and the behavior is to produce a string that consists of the type name, and the object’s identity hashcode.
The Concatenation operator is specified to create a new String
object, except in the case where the expression is a Constant Expression. In the latter case, the expression is evaluated at compile type, and its runtime value is equivalent to a string literal. This means that there is no runtime overhead in splitting a long string literal like this:
String typing = "The quick brown fox " +
"jumped over the " +
"lazy dog"; // constant expression
As noted above, with the exception of constant expressions, each string concatenation expression creates a new String
object. Consider this code:
public String stars(int count) {
String res = "";
for (int i = 0; i < count; i++) {
res = res + "*";
}
return res;
}
In the method above, each iteration of the loop will create a new String
that is one character longer than the previous iteration. Each concatenation copies all of the characters in the operand strings to form the new String
. Thus, stars(N)
will:
N
new String
objects, and throw away all but the last one,N * (N + 1) / 2
characters, and