Sobes.tech
Junior

How is a string pool initially created in Java?

sobes.tech AI

Answer from AI

In Java, the String Pool is created automatically when a class is loaded and contains all string literals encountered in the code. When a string literal is used in a program, for example "hello", the JVM checks if such a string already exists in the pool. If it does, it returns a reference to it; if not, it adds a new string to the pool.

This helps save memory, as identical string literals are stored in a single instance. The String Pool is created in a special area of memory (in modern JVMs — in the heap, in older versions — in PermGen).

Example:

String s1 = "test";
String s2 = "test";
System.out.println(s1 == s2); // true, both variables refer to the same object in the pool

Thus, initially, the String Pool is formed from all string literals encountered in loaded classes.