/* * File: TestStringEquals.java * Author: Java, Java, Java * Description: This program illustrates the differences * between the == operator and the equals() method as * applied to String objects. The == operator implements * string identity, where two string references are identical if * they refer to the same object. The equals() method * implements string equality, where two strings are equal * if they contain the same characters in the same order. */ import java.awt.*; public class TestStringEquals { static String s1 = new String("hello"); // s1 and s2 are equal, not identical static String s2 = new String("hello"); static String s3 = new String("Hello"); // s1 and s3 are not equal static String s4 = s1; // s1 and s4 are identical static String s5 = "hello"; // s1 and s5 are not identical static String s6 = "hello"; // s5 and s6 are identical private static void testEqual(String str1, String str2) { if (str1.equals(str2)) System.out.println(str1 + " equals " + str2); else System.out.println(str1 + " does not equal " + str2); } // testEqual() private static void testIdentical( String str1, String str2 ) { if (str1 == str2) System.out.println(str1 + " is identical to " + str2); else System.out.println(str1 + " is not identical to " + str2); } // testIdentical() public static void main(String argv[]) { testEqual(s1, s2); // equal testEqual(s1, s3); // not equal testEqual(s1, s4); // equal testEqual(s1, s5); // equal testEqual(s5, s6); // equal testIdentical(s1, s2); // not identical testIdentical(s1, s3); // not identical testIdentical(s1, s4); // identical testIdentical(s1, s5); // not identical testIdentical(s5, s6); // identical } // main() }// TestStringEquals