How do objects get into the String Pool?
sobes.tech AI
Answer from AI
Objects of the String class are added to the String Pool mainly in two ways:
-
Using a string literal: When you create a string using a literal (for example,
"hello"), the Java Virtual Machine (JVM) first checks the String Pool. If a string with the same content already exists, a reference to it is returned. Otherwise, a new string is created in the String Pool, and a reference to the new object is returned.// String literal String s1 = "hello"; // The object "hello" is created or found in the String Pool String s2 = "hello"; // s2 gets a reference to the same "hello" object from the String Pool -
Calling the
intern()method: Theintern()method is called on aStringobject and returns the canonical representation of the string. If a string with the same content already exists in the String Pool, a reference to it is returned. If not, the string is added to the String Pool, and a reference to the added object is returned.// Creating a string via new String s3 = new String("world"); // A new "world" object is created in the heap, not in the String Pool // Using the intern() method String s4 = s3.intern(); // "world" is added to the String Pool (if not already there), and s4 gets a reference to it String s5 = "world"; // s5 gets a reference to the "world" object from the String Pool (the same as s4)
Thus, the String Pool serves to cache frequently used string literals, optimizing memory usage, since different references can point to the same string object in the pool. Strings created via new String(...) are initially not placed in the pool until the intern() method is explicitly called.