Member-only story
How exactly String Pool Works in Java?
Let me deep dive in to make you understand back story.
Have you ever wondered why these two lines return true?
String a = "java";
String b = "java";
System.out.println(a == b);And then this one returns false?
String a = new String("java");
String b = new String("java");
System.out.println(a == b);Same text. Different result. Same language. Different behavior.
So what is Java really doing behind the scenes?
The answer is the String Pool.
Think of it like a shared shelf
Imagine a library where popular books are kept on a special shelf.
If ten people ask for the same book, the library does not print ten separate copies. It gives everyone a reference to the same book.
That is exactly how Java handles string literals.
When you write:
String s1 = "hello";Java first checks the String Pool.
- If
"hello"already exists there, Java reuses it. - If it does not exist, Java creates it and stores it in the pool.
So when you write:
String s2 = "hello";s2 points to the same pooled object as s1.







