I'm trying to understand reference comparing in Java. Let's assume we have the following main code:
public static void main (String args[]) {
String str1 = "Love!";
String str2 = "Love!";
String str3 = new String("Love!");
String str4 = new String("Love!");
String str5 = "Lov"+ "e!";
String str6 = "Lo" + "ve!";
String s = "e!";
String str7 = "Lov"+ s;
String str8 = "Lo" + "ve!";
String str9 = str1;
}
I understand that str1 == str2 == str5 == str6 == str8 == str9
and all of them are the same reference to the common pool. (value "Love!").
s
is a reference to the common pool as well, but it refers the value "e!"
I understand also that str1 != s
.
I know that str3
, str4
are references to the HEAP, and each of them is a different Object. str3 != str4
.
I do NOT understand why str1 != str7
, and I would love to get an explanation.
In
String s = "e!";
String str7 = "Lov"+ s;
While "e!"
is a constant expression, s
is not a constant variable (JLS §4.12.4); therefore, "Lov" + s
, which references s
, cannot be a constant expression (JLS §15.28). In order for a variable like s
to be a constant variable, it needs to be both final
and initialized from a constant expression.
If you had written
final String s = "e!";
String str7 = "Lov" + s;
then str1 == str7
would have been true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With