Java Interview Question: String Pool vs Heap Memory

A simple Java interview question… that isn’t so simple 👇 class Main { public static void main(String[] args) { String name = "Srishti"; String b = new String("Srishti"); String c = name; String d = b; System.out.println(name == b); System.out.println(name == c); } } I was asked this in an interview and it’s a perfect example of how fundamentals matter more than complexity. Most people expect both outputs to be true. But the actual result is: false true 💡 Why? Because in Java: 🔹 "Srishti" is stored in the String Pool (optimized memory) 🔹 new String("Srishti") creates a new object in Heap 🔹 c = name → same reference 🔹 d = b → same reference ⚡ The key insight: == compares memory reference, not content 👉 name == b → false (different objects) 👉 name == c → true (same object) If you actually want to compare values: name.equals(b); // true 📌 What this question really tests: Not syntax. Not memorization. But your understanding of how Java handles memory. #Java #CodingInterview #SoftwareEngineering #Programming #Developers #TechCareers

To view or add a comment, sign in

Explore content categories