Senior
Where are strings stored in Java?
sobes.tech AI
Answer from AI
In Java, strings (objects of the String class) are stored in different places depending on the JVM version and context:
-
String Pool — a special area in memory where string literals and strings explicitly placed in the pool using
String.intern()are stored. In modern JVMs, the string pool is located in the heap, not in PermGen as in older versions. -
Heap —
Stringobjects are created in the heap if they are created dynamically (for example, vianew String("text")).
Thus, string literals are stored in the string pool, which is optimized for reusing identical strings, while other String objects are stored in the heap. This helps save memory and speeds up string comparison.
Example:
String s1 = "hello"; // string literal, stored in the pool
String s2 = new String("hello"); // object in the heap
String s3 = s2.intern(); // returns a reference to the string from the pool