Testing for Equality with equals()

That's not what you expected. To compare strings or any other kind of object you need to use the equals(Object o) method from java.lang.String. Below is a corrected version that works as expected. The reasons for this odd behavior go fairly deep into Java and the nature of object data types like strings.

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.equals(s2) ) {
      System.out.println("The strings are the same.");
    else {
      System.out.println("The strings are not the same.");

Previous | Next | Top | Cafe au Lait

Copyright 1997-8 Elliotte Rusty Harold
Last Modified January 26, 1998