Testing Objects for Equality

<, >, <= and >= can only be used with numbers and characters. They cannot be used with Strings, booleans, arrays or other compound types since there's no well-defined notion of order for these objects. Is true greater than false? Is "My only regret is that I have but one life to give for my country" greater than "I have a dream"?

Equality is a little easier to test however. true is equal to true and true is not equal to false. Similarly "My only regret is that I have but one life to give for my country" is not equal to "I have a dream." However you might be surprised if you ran this program:

class JackAndJill {

  public static void main(String args[]) {

    String s1 = new String("Jack went up the hill.");
    String s2 = new String("Jack went up the hill.");

    if ( s1 == s2 ) {
      System.out.println("The strings are the same.");
    }

    else if ( s1 != s2 ) {
      System.out.println("The strings are not the same.");
    }
  }
}

The result is

The strings are not the same.

Previous | Next | Top | Cafe au Lait

Copyright 1997-8 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified January 26, 1998