When I run this code
String a="sa";
String s = "s";
String b=s + "a";
System.out.println(b==a);
It prints false. How? Is b a new String object?
When I run this code
String a="sa";
String s = "s";
String b=s + "a";
System.out.println(b==a);
It prints false. How? Is b a new String object?
You are partly correct, the +
operator will create a new String
object if the expression is not a constant expression.
According to the Java Language Specification Section 15.18.1,
(emphasis mine)
§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.The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.
The String object is newly created (§12.5) unless the expression is a constant expression (§15.28).
By constant expression, it means something like:
"a" + "b" // this will always evaluate to "ab", so it's constant.
or
a + b
where a
and b
are declared final
.
See §15.28 for details.
It creates new string because you are concatenating with object instances.
If you want to use already exists string from string pool you should concatenate with constant expressions.
In your case if you want a==b to be true you should use intern as below :
String b= (s + "a").intern();
System.out.println(b==a);
Or you can use constans expression:
String b= "s" + "a"
System.out.println(b==a);
It also prints true