public static void main(String[] args) {
String a = new String("lo").intern();
final String d = a.intern();
String b = "lo";
final String e = "lo";
String c = "Hello";
System.out.println(b==a);//true
System.out.println(d==a);//true
System.out.println(e==a);//true
System.out.println(c=="Hel"+a); //why is this false? when e==a is true
System.out.println(c=="Hel"+d); //why is this false?
System.out.println(c=="Hel"+b); //why is this false?
System.out.println(c=="Hel"+e); //this is true
}
This results in
true
true
true
false
false
false
true
The expression e==a
is true implies same reference. So why the last expression is true but the 4th to last ie c== "Hel"+a
is false?
In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned.
String Interning is a process of storing only one copy of each distinct string value in memory. This means that, when we create two strings with the same value - instead of allocating memory for both of them, only one string is actually committed to memory. The other one just points to that same memory location.
The Java String intern() method returns a canonical representation of the string object. Here, string is an object of the String class.
The Intern method uses the intern pool to search for a string equal to the value of str . If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to str is added to the intern pool, then that reference is returned.
The expression
"Hel" + a
Is not a compile time constant. Actually, it compiles to:
new StringBuilder().append("Hel").append(a).toString()
(or similar) which creates a new String object at runtime.
However, because e
is final, the compiler can determine that the concatenation of "Hel"
and e
's value is a constant value, and so interns it.
all these strings are calculated in runtime, this is why they are different
System.out.println(c=="Hel"+a); //why is this false? when e==a is true
System.out.println(c=="Hel"+d); //why is this false?
System.out.println(c=="Hel"+b); //why is this false?
this one calculated during compile time, because e is final:
System.out.println(c=="Hel"+e); //this is true
if you change code to this:
System.out.println(c==("Hel"+a).intern()); //why is this false? when e==a is true
System.out.println(c==("Hel"+d).intern()); //why is this false?
System.out.println(c==("Hel"+b).intern()); //why is this false?
all of them will produce 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