Java String Compare
In Java, you can compare two strings to determine if they are equal in value or not. There are two ways to compare strings:
Equality operator ==
The equality operator == compares the reference of two strings, not their values. This means that if two strings are created with the same value but stored in separate memory locations, they will not be equal according to the equality operator.
equals() method compares the value of two strings, not their references. This means that even if two strings are stored in separate memory locations, they will be considered equal if they have the same value.
String str1 = "Hello"; String str2 = "Hello"; String str3 = new String("Hello"); System.out.println(str1 == str2); // Output: true System.out.println(str1 == str3); // Output: false System.out.println(str1.equals(str3)); // Output: true
It is recommended to use the
equals() method when comparing the values of two strings, because it provides a more reliable and accurate comparison.