public class D2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1="java";
String s2="ja".concat("va");
System.out.println(s1==s2);
}
}
On concatenating two String constants in s2 doesn't result in a new String object(String objects are only created when new is used or a perm reference like s1 on concatenation). Kindly shed light on why the o/p is false.
On concatenating 2 String constants in s2 doesn't result in a new String object
That's true when it's performed with the string concatenation operator - but that's not what you're doing here. You're manually calling String.concat
, so this is not a constant expression, and not evaluated at compile time.
If you used:
String s2 = "ja" + "va";
then the concatenation would be performed by the compiler, and s1
and s2
would refer to the same object.
JLS section 15.28 gives details around what leads to a constant expression, and that doesn't include method calls.
See more on this question at Stackoverflow