How to compare two String object?
- If you want to compare two String object based on some specific attributes, you have to override the equal() method.
- If you compare two objects by the equal operator, it will compare by reference variable.
Example:
public class StringComparisonExample {
public static void main(String[] args) {
String str1 = new String(“Hello”);
String str2 = new String(“Hello”);// Using == operator (compares references)
System.out.println(“str1 == str2: ” + (str1 == str2)); // false// Using equals() method (compares content)
System.out.println(“str1.equals(str2): ” + str1.equals(str2)); // true
}
}