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.
str1 == str4
, then you need to forget what you think you know, because it is not.str3
,str4
, andstr7
are all 3 independent objects. – Accumulatestatic final
constants).s
is a variable, which is whystr7
doesn't fall into that case. – Keis
is not a constant,str7
is a new string. – Accumulate