![]() |
VOOZH | about |
The Java String Pool (also called the String Intern Pool) is a special memory area inside the heap that stores string literals.
When the JVM encounters a string literal:
This mechanism reduces memory consumption by reusing immutable string objects.
When a string is declared in Java, two separate memory areas are involved:
Example:
String str1 = "Hello";
Here, the variable str1 is stored in the stack, while "Hello" is stored in the String Constant Pool inside the heap.
Yes
Both s1 and s2 refer to the same "abc" object in the String Constant Pool, so their references are identical.
new KeywordNo
Using the new keyword forces the JVM to create new objects in the heap outside the String Constant Pool, even if an identical value already exists there. Hence, s1 and s2 refer to different heap objects.
When a string is created, Java determines how to allocate memory based on its declaration type:
Behavior:
Memory Representation:
new KeywordBehavior:
Memory Representation: