The only way to avoid creating a new String
object each time you evaluate this expression is to make sure that it is a compile-time constant.
As it says in JLS Sec 15.28:
Constant expressions of type String are always "interned" so as to share unique instances
You can make use of this by declaring the strings final
, and using +
to concatenate them:
String s1 = "abc";
String s2 = "pqr";
// false, because s1+s2 is evaluated twice.
System.out.println((s1 + s2) == (s1 + s2));
final String s3 = "abc";
final String s4 = "pqr";
// true, because s3+s4 is a constant, and thus the compiler puts the
// value in the constant pool.
System.out.println((s3 + s4) == (s3 + s4));
// false, because the results of method calls aren't compile-time
// constant.
System.out.println(s3.concat(s4) == s3.concat(s4));
Ideone demo
If the strings you're joining aren't compile time constants, you can't avoid creating a new string, because of String
's immutability.