Junior — Middle
Where in Java storage memory are string objects located?
sobes.tech AI
Answer from AI
In Java, string objects (String) are stored in a special memory area called the String Pool, which is located in the Metaspace or in PermGen (in older JVM versions).
When a string literal is created, the JVM checks the string pool: if such a string already exists, a reference to the existing object is returned; otherwise, a new object is created and placed in the pool. This helps save memory and speeds up string comparison.
If a string is created using the constructor new String(), the object is created in the heap, not in the pool, and will not be automatically placed in the String Pool until the intern() method is explicitly called.
Example:
String s1 = "hello"; // string in the pool
String s2 = new String("hello"); // object in the heap
String s3 = s2.intern(); // s3 refers to the string from the pool