Wednesday, June 15, 2005

The equals Method

Introduction

The equals method checks objects for equality. The default behavior inherited from class Object is simply to check if the references points to the same object.

public boolean equals(Object obj) {
    return (this == obj);
}

Program

package bloggingjava;

public class Main {
    public static void main(String[] args) {
        String s1 = "ABC";
        String s2 = "ABC";
        String s3 = new String("ABC"); // bad code
        
        System.out.println(s1 == s2);
        System.out.println(s1 == s3);
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));
    }
}

Output

true
false
true
true

Discussion