# JAVA String pool
[JAVA memory- STACK vs HEAP](/z_wC1OEaTvq5JUwwfClyiQ)
###### tags: `STRINGPOOL`
ref: https://www.baeldung.com/java-string-pool
---
### StringPool
the JVM can optimize the amount of memory allocated for them by storing only one copy of each<b> literal String</b> in the pool. This process is called <b>interning</b>.
When we create a String variable and assign a value to it, the JVM searches the pool for a String of equal value.
If found, the Java compiler will simply return a reference to its memory address, without allocating additional memory.
If not found, it'll be added to the pool (interned) and its reference will be returned.
---
### String literal vs String Object
| String | literal | object |
| -------- | -------- | -------- |
| create | String constantString = "Baeldung"; | String newString = <b>new</b> String("Baeldung"); |
|store | string pool in HEAP | new addr in HEAP |
In general, we should use the String literal notation when possible. It is easier to read and <b>it gives the compiler a chance to optimize our code</b>.
---
### Manual intern
find this string in string pool and return its ref
```java=
String constantString = "interned Baeldung";
String newString = new String("interned Baeldung");
assertThat(constantString).isNotSameAs(newString);
String internedString = newString.intern();
assertThat(constantString)
.isSameAs(internedString);
```
---
### string pool GC after JAVA 8
before java8 : string pool in perm space which cant do GC and lead to OOM Exception.
PermGen space: in the PermGen space, which has a fixed size — it can't be expanded at runtime and is not eligible for garbage collection
after java8 : string pool in heap and can be GC