Java Interview Question: String Pool and Memory References

A simple Java interview question 👇 class Main { public static void main(String[] args) { String name = "Hello"; String b = new String("Hello"); 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: 🔹 "Hello" is stored in the String Pool (optimized memory) 🔹 new String("Hello") 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

One thing I learnt is check the code before replying or answering

Like
Reply

One important nuance - new String("Hello") actually creates two objects: one in the String Pool and one in the heap. Also, adding b.intern() would make this even more interesting from an interview perspective. Nice fundamentals check overall.

See more comments

To view or add a comment, sign in

Explore content categories