Junior — Middle
How does memory allocation occur when creating a new string in programming?
sobes.tech AI
Answer from AI
In Java, strings (objects of the String class) are immutable. When a new string is created, memory is allocated in the heap where the String object is stored.
If a string is created as a literal, for example:
String s = "hello";
then the JVM places it in the string pool — a special area in memory for reusing string literals.
If a string is created via the constructor:
String s = new String("hello");
then a new memory area is allocated in the heap, and a new object is created, even if such a string already exists in the pool.
Thus, memory allocation depends on the method of creating the string, but it always occurs in the heap, and the string pool helps save memory by reusing literals.