Site hosted by Angelfire.com: Build your free website today!
 

The equals() method

Unless it is overridden, the equals() method behaviour in Object, performs the same reference comparison as the == operator. However, the Boolean and String classes override this with a more meaningful comparison. equals() returns true, in Booleans if the two objects contain the same Boolean value, and in String if the Strings contain the same sequence of characters.

class EqString {
    static String s1 = "This is a test";
    public static void main(String[] args) {
        String s2 = "This is a test";
        String s3 = new String("This is a test");
        if (s1.equals(s3))
            System.out.println("s1 equals s3");
        if (s1 == s2)
            System.out.println("s1 == s2");
        if (s1 == s3)
            System.out.println("s1 == s3");
    }
}
s1 equals s3
s1 == s2

The Java compiler maintains a record of String objects declared in a class. The compiler reuse the String objects when appropriate (with the same string literal), therefor s1 and s2 in the above example actually referes to the same object.