Java automatically puts string literals. This means that in many cases the == operator works for strings in the same way as for int or other primitive values.
Since interning is automatic for string literals, the intern() method should be used for strings constructed with new String()
Using your example:
String s1 = "Shoaib"; String s2 = "Shoaib"; String s3 = "Shoaib".intern(); String s4 = new String("Shoaib"); String s5 = new String("Shoaib").intern(); if ( s1 == s2 ){ System.out.println("s1 and s2 are same");
will return:
s1 and s2 are same s1 and s3 are same s1 and s5 are same
The explanation in simple words:
-> In String pooled region , if we assume that we have "Shoaib" as a string, the link of which is 2020
-> Now, any object created using new String("Shoaib") will point to another link: 3030
-> But if you want to assign a reference from "Shoaib" in String of the merged region to new String("Shoaib") , then we use intern () on it.
So, above, you asked that the βvalueβ .intern () does not make sense in the case of internment.
Shoaib chikate
source share