// strings and references: $equals$ vs $==$ public class string_equals { public static void main(String[] args) { // Create 2 strings with reference variables $s1$ and $s2$. // Remember that $s1$ and $s2$ are REFERENCES to String objects String s1 = new String("hi"); String s2 = new String("hi"); // So, are $s1$ and $s2$ equal? if (s1 == s2) System.out.println("Test 1: equal!"); else System.out.println("Test 1: not equal!"); // No! $s1$ and $s2$ do NOT refer to the same object! // Each time you use $new$ to create a String, Java creates // an entirely new object, even if it looks the "same" as another. // To test equality of two objects, use the $equals()$ method // from the $Object$ class. if (s1.equals(s2)) System.out.println("Test 2: equal!"); if (s2.equals(s1)) System.out.println("Test 3: equal!"); // What if you attempt to make an alias? s2 = s1; // $s2$ gets the address of the $s1$ object // Yes, an alias means equal addresses: if (s1 == s2) System.out.println("Test 4: equal!"); // Yes, an alias means the same object: if (s1.equals(s2)) System.out.println("Test 5: equal!"); // What if you attempt something like String addition? if (s1.equals("h"+"i")) System.out.println("Test 6: equal!"); // Yes, now you have equal Strings // Can you check String literals with $==$ ? Yes: if ("hi" == "hi") System.out.println("Test 7: equal!"); // The following works, too: if ("hi".equals("hi")) System.out.println("Test 8: equal!"); // Uh oh...what if you try the following: String x = "hi"; String y = "hi"; // Can you use the $==$ operator to check the contents of $x$ and $y$? if (x == y) System.out.println("Test 9: equal!"); // Yes, Java now thinks $x$ and $y$ are aliases and refer to // the same String. When you create a String literal Java will reuse // that object if you write the literal again. Note that you do NOT // see this behavior when using $new String(....)$. // To be safe, you should avoid $==$ with Strings and use $equals()$: if (x.equals(y)) System.out.println("Test 10: equal!"); } } /* ouput: Test 1: not equal! Test 2: equal! Test 3: equal! Test 4: equal! Test 5: equal! Test 6: equal! Test 7: equal! Test 8: equal! Test 9: equal! Test 10: equal! */