Why == Fails for String Comparison
What you'll learn: You'll discover why using == to compare strings often gives you unexpected results—and the surprising cases when it accidentally works.
The Problem with == and Strings
You already know that == compares memory addresses for reference types, not the content of objects. This causes major headaches with strings because two strings can hold identical text but live at different memory locations.
String greeting1 = new String("Hello");
String greeting2 = new String("Hello");
System.out.println(greeting1 == greeting2); // false — different addresses!
Even though both strings contain "Hello", == returns false because greeting1 and greeting2 point to two separate objects on the heap.
When == Accidentally "Works"
Here's the confusing part: sometimes == appears to work with strings:
String color1 = "blue";
String color2 = "blue";
System.out.println(color1 == color2); // true — huh?!
This works because Java uses something called the string pool for string literals. When you write "blue" directly in code, Java reuses the same object for efficiency. Both color1 and color2 point to the same memory address, so == returns true.
But relying on this is dangerous—you never know when Java will create a new object instead.
The Lesson
Using == for strings is like checking if two people live at the same house address instead of checking if they have the same name. Sometimes they do live together (string pool), but usually they don't (separate objects with new).
Key Takeaway: Never use == to compare string content—it compares memory addresses and will fail unpredictably. Always compare strings by their content using the proper method (which you'll learn next).