I read quite some answers about the String.intern() method but didn't quite get my answer. The intern method is a native method with the docs saying :
Returns a canonical representation for the string object.
Now String is a wrapper around the char[] array. When we define using literals, the reference is direct to the underlying char[].
When we create using - new String(), it creates an object on the heap and one part of the object hold the "value", which internally refers to the underlying char[] Array.
My questions are :
- Is the char[] being cached as a HashSet? Hence when pooling, there is no duplicate char[] ?
- The intern() method when called -
String s = new String().intern()
, the local reference now directly points/refernces to the char[] and the String type object created is not having a live reference ? (my assumptions based on -"hello" == "hello".intern() = true
)
The question rather is - How does the intern() method work internally.