All.I have a java code snippet like this:
String a = new StringBuilder("app").append("le").toString();
System.out.println(a.intern() == a);
String b = new StringBuilder("orange").toString();
System.out.println(b.intern() == b);
and this java code will output true,false. I wonder why. Thanks All.
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.
append() method is used to append the string representation of some argument to the sequence.
concat() method takes concatenates two strings and returns a new string object only string length is greater than 0, otherwise, it returns the same object. + operator creates a new String object every time irrespective of the length of the string.
In both cases, StringBuilder.toString()
creates a new string.
In the first case, String.intern()
finds that there's no string "apple" in the intern pool, so adds the provided one to the pool and returns the same reference - which is why it prints true
.
In the second case, String.intern()
finds that there's already a string "orange" in the intern pool, so returns a reference to that - which is a different reference to b
, hence it prints false
.
Note that if you had a line before the start of this code of:
System.out.println("apple");
then you'd see false
from the first comparison too, for the same reason.
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