Program 5.2: A Correct Test for String Equality

To compare Strings you need to use the equals(String s) method from java.lang.String. Program 5.2 is a corrected version that works as expected. The reasons for this odd behavior go fairly deep into Java and the nature of compound data types like Strings. Youšll learn more about this in the next four chapters and then again in Chapter 22 on data structures.

class JackAndJill {

  public static void main(String args[]) {
    String s1 = "Jack went up the hill.";
    String s2 = "Jack went up the hill.";
    if (s1.equals(s2)) {
        "The strings are the same.");
    else  {
      "The strings are different.");


Copyright 1996 Elliotte Rusty Harold
This Chapter