Junior — Middle
How can a string pool be implemented in Java heap?
sobes.tech AI
Answer from AI
In Java, a string pool in the heap can be implemented using the String.intern() method. This method returns the canonical representation of the string from the string pool, meaning if a string with the same content already exists in the pool, a reference to it is returned; otherwise, the string is added to the pool.
Example:
String s1 = new String("hello");
String s2 = s1.intern();
String s3 = "hello";
System.out.println(s2 == s3); // true
Thus, intern() helps save memory by avoiding duplicate strings in the heap. However, it should be used with caution, as excessive use can increase the load on the string pool and garbage collector.