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

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.

This question has already been answered. Start a new discussion instead.