Junior — Middle
Kus Java salvestusmälu mälu asuvad stringi objekti?
sobes.tech AI
Vastus AI-lt
In Java, string objects (String) are stored in a special memory area called String Pool (string pool), which is located in 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 on the heap and is not 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 on the heap
String s3 = s2.intern(); // s3 references the string in the pool