<<< Comparing Strings to null | Index | Logical operators >>> |
The following code detects whether two strings refer to the same object in memory:
Scanner sc = new Scanner(System.in); System.out.print("Enter string1: "); String string1 = sc.next(); System.out.print("Enter string2: "); String string2 = sc.next(); if (string1 == string2) // this will always be false! System.out.println("string1 = string2"); else System.out.println("string1 not = string2");
NOTE: Because Java stores string literals such as "Hello" in pools to reduce duplication, the equality and inequality tests for strings may not work as shown above when two String objects are assigned the same literal value.
<<< Comparing Strings to null | Index | Logical operators >>> |