intern() is an interesting function in the java.lang.String object. The intern() function eliminates duplicate string objects from the application and has the potential to reduce the overall memory consumption of your application. In this post, let’s learn more about this intern() function.
1. How Does the String intern() Function Work?
In Java heap memory, a pool of string objects is maintained. When you invoke an intern() function on a string object, JVM will check whether this string object already exists in the pool. If it exists, then that same object is returned back to the invoker. If the string object doesn’t exist, then this string object is added to the pool, and the newly added string object is returned to the invoker.