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

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.