There is code as following:
String s = new String("1");
s.intern();
String s2 = "1";
System.out.println(s == s2);
String s3 = new String("1")+new String("1");
s3.intern();
String s4 = "11";
System.out.println(s3 == s4);
Output of the code above is:
false
true
I know that s
and s2
are different objects, so the result evaluates to false, but the second result evaluates to true. Can anyone tell me the difference?
String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. By applying String. intern() on a couple of strings will ensure that all strings having the same contents share the same memory.
intern() The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool. Note that, if another String with the same contents exists in the String constant pool, then a new object won't be created and the new reference will point to the other String.
intern() in Java. All compile-time constant strings in Java are automatically interned using this method. String interning is supported by some modern object-oriented programming languages, including Java, Python, PHP (since 5.4), Lua,Julia and .
The intern() method creates an exact copy of a String that is present in the heap memory and stores it in the String constant pool. Takeaway - intern() method is used to store the strings that are in the heap in the string constant pool if they are not already present.
Here's what's happening:
String s1 = new String("1");
s1.intern();
String s2 = "1";
"1"
(passed into the String
constructor) is interned at address A.s1
is created at address B because it is not a literal or constant expression.intern()
has no effect. String "1"
is already interned, and the result of the operation is not assigned back to s1
.s2
with value "1"
is retrieved from the string pool, so points to address A.Result: Strings s1
and s2
point to different addresses.
String s3 = new String("1") + new String("1");
s3.intern();
String s4 = "11";
s3
is created at address C.intern()
adds the string with value "11"
at address C to the string pool.s4
with value "11"
is retrieved from the string pool, so points to address C.Result: Strings s3
and s4
point to the same address.
String "1"
is interned before the call to intern()
is made, by virtue of its presence in the s1 = new String("1")
constructor call.
Changing that constructor call to s1 = new String(new char[]{'1'})
will make the comparison of s1 == s2
evaluate to true because both will now refer to the string that was explicitly interned by calling s1.intern()
.
(I used the code from this answer to get information about the strings' memory locations.)
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