The compiler replaces multiple value-equal Strings built from Constant Expressions like this:
String myStr1 = "good";
String myStr2 = ""+'g'+'o'+'o'+'d';
System.out.println(myStr1==myStr2);
With a unique String object obtained from String.intern. That unique String object is then assigned to both variables. This is why they are then reference equal.
String myStr1 = "good";
char[] myCharArr = {'g', 'o', 'o', 'd' };
String myStr2 = ""+myCharArr[0]+myCharArr[1]+myCharArr[2]+myCharArr[3];
System.out.println(myStr1==myStr2);
The compiler cannot optimize this because it has an array reference which is not a Constant Expression. This results in two separate String objects which are not reference equal. It would violate the Java Language Specification to do otherwise.
Here is the definition of a Constant Expression from the Java Language Specification:
A constant expression is an expression denoting a value of primitive
type or a String that does not complete abruptly and is composed using
only the following:
Literals of primitive type and literals of type String (§3.10.1,
§3.10.2, §3.10.3, §3.10.4, §3.10.5)
Casts to primitive types and casts to type String (§15.16)
The unary operators +, -, ~, and ! (but not ++ or --) (§15.15.3,
§15.15.4, §15.15.5, §15.15.6)
The multiplicative operators *, /, and % (§15.17)
The additive operators + and - (§15.18)
The shift operators <<
, >>
, and >>>
(§15.19)
The relational operators <
, <=
, >
, and >=
(but not instanceof) (§15.20)
The equality operators ==
and !=
(§15.21)
The bitwise and logical operators &, ^, and | (§15.22)
The conditional-and operator && and the conditional-or operator || (§15.23, §15.24)
The ternary conditional operator ? : (§15.25)
Parenthesized expressions (§15.8.5) whose contained expression is a constant expression.
Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
Qualified names (§6.5.6.2) of the form TypeName . Identifier that refer to constant variables (§4.12.4).
Constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.
A constant expression is always treated as FP-strict (§15.4), even if
it occurs in a context where a non-constant expression would not be
considered to be FP-strict.
SOURCE: http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#d5e30892