Java String Comparison: == vs equals()

Java Interview Tip: s1 == s2 vs s1.equals(s2) Many Java developers get confused between == and .equals() when comparing strings. Here’s the simple difference 🔹 s1 == s2 Checks reference equality. It verifies whether both variables point to the same object in memory. String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1 == s2); // false Even though the values look the same, Java created two different objects. 🔹 s1.equals(s2) Checks value equality. It compares the actual content of the strings. System.out.println(s1.equals(s2)); // true A small concept, but a very common Java interview question. What will be the output? String str1 = "Java"; String str2 = "Ja" + "va"; System.out.println(str1 == str2); 📊 Your answer? A️. true B️. false C️. Compilation error D️. Depends on JVM Let’s see who gets it right! #Java #Programming #JavaDeveloper #CodingInterview #SoftwareDevelopment

  • graphical user interface

In Java, string literals are stored in the String Pool. "Java" is placed in the string pool. "Ja" + "va" is a compile-time constant expression. The compiler optimizes it during compilation and converts it to "Java". So effectively the code becomes: String str1 = "Java"; String str2 = "Java"; Both str1 and str2 point to the same object in the String Pool. Therefore: str1 == str2 → true == compares memory references, not string content. Since both references point to the same pooled object, it returns true

Like
Reply

To view or add a comment, sign in

Explore content categories