Java String Puzzle: Same Value, Different Results

💡 Java Puzzle: Same Value, Different Results? Take a look 👇 String s1 = "ja" + "va"; String s2 = "java"; System.out.println(s1 == s2); Now guess… What will it print? 🤔 A) true B) false --- ⬇️ Answer: ✅ true ⚙️ Why: Because both "ja" and "va" are compile-time constants. The Java compiler optimizes and concatenates them at compile time, so s1 and s2 actually point to the same string literal in the String Pool. BUT here’s the twist 👇 Try this instead: String part = "va"; String s1 = "ja" + part; String s2 = "java"; System.out.println(s1 == s2); Now the result is ❌ false Why? Because when you use a variable, concatenation happens at runtime, creating a new String object — not the same pooled literal. --- 🧠 Moral: Even though String is immutable, the way you build it — at compile-time vs runtime — determines whether it lives in the String Pool or the Heap. --- 💬 How many of you knew this subtle compiler optimization existed? Or ever got caught by it in an interview? 😅 #Java #CoreJava #StringPool #Compiler #Programming #Developers #InterviewQuestion

Nice puzzle - quick rule: 1. prefer StringBuilder (or String.join) for repeated concatenation to avoid creating many temporary String objects 2. Always compare strings with .equals(...) (or Objects.equals(...)) — == checks reference identity, not content. Compile-time literal concatenation is one of those subtle Java details worth remembering.

To view or add a comment, sign in

Explore content categories