Why String comparison with '==' is illegal,eventhough it works fine.Kindly explain?

Dani AI

Generated

As already pointed out, the important distinction is reference identity versus content equality. A few practical points that weren't in the thread and are useful when this question comes up later:

String interning: Java keeps a pool of literal strings created at compile time. Two identical string literals will usually share the same reference, so == can appear to "work" for them. Concatenation of compile-time constants is folded by the compiler into a single literal and will also be interned. Creating strings at runtime (for example with new String(...) or runtime concatenation) produces distinct objects unless intern() is used.

Null-safety and common idioms: Calling equals() on a null reference throws NPE. Use a null-safe check instead — either put the literal first or use Objects.equals(...) (Java 7+). For example:

Objects.equals(a, b)   // returns true if both null or if a.equals(b)
"constant".equals(var) // avoids NPE when var is null

When to use ==: It's correct for identity checks (are these the exact same object). That is useful for enums (use ==) and occasional identity-based logic. It is not the right choice for content comparison of Strings in general.

Extras for custom types: As suggested, override equals() together with hashCode() when logical equality is required. Collections (HashMap, HashSet) and other APIs depend on both methods behaving consistently.

Caveat about intern(): Interning can make reference comparisons possible, but it affects memory and lifetime; use it sparingly and only when there is a proven benefit.

Recommended Answers

All 4 Replies

If you run this code you will see that '==' doesn't work:

public static void main(String [] args) {
        String s1 = new String("aa");
        String s2 = new String("aa");
        
        System.out.println(s1==s2); // false
        System.out.println(s1.equals(s2)); // true
    }

The '==' checks if they are the same object and the equals their value. String is an object and you should treat it as such. Meaning that for objects if you want to check if they are equal use the "equals" method.

If you create an object of your own with private attributes/properties and you want to compare 2 of those then you should use the equals method. But since you wrote that class, you must implement/override the equals method.

Especially if you want to put that object in a List(Vector, ArrayList). The methods that they have for searching in the list, use the "equals" method of the object they contain. If you put java objects then that's ok because they already have that method. But for your own objects, your class must implement/override the equals method.

There is a code with action listener at the java gui where at the action performed method we use this '==' instead of equals.

private JButton butt = new JButton("Click here.");

public void actionPerformed(ActionEvent e) {
  Object src = e.getSource();
  if (src[B]==[/B]butt) {
     // button was clicked
  }
}

We use the '==' in this case because that method (getSource) returns the same instance of the object (the butt instance itselfm not a new one), so the '==' will work.

But for other objects that we create, the equals should be used.

Thanks a lot.. nice explanation.. which clears my doubt very comfortably.

Also it is best when you implement/override the equals method in your objects then you should also implement/override the hashCode method:
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#hashCode()

There are many examples on how to implement it. There are many ideas. The more complex provide better performance when you put your objects into a Hashtable.

Thanks for the info.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.