There are 3 ways to compare strings in Java:
- using equals() method
- using == operator
- using compareTo() method
class StringCompareExample {
public static void main(String args[]) {
String s1 = "test";
String s2 = "test";
String s3 = "Test";
String s4 = new String("Test");
// EQUALS (compares values)
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false
// ignoring case
System.out.println(s1.equalsIgnoreCase(s3)); // true
// == (compares references not values)
System.out.println(s1 == s2); // true (refers to same instance)
System.out.println(s1 == s4); // false (s4 created in nonpool)
// COMPARETO (returns integer value)
// --> 0 if strings have same value
// --> -1 if first string value is less than second string value
// --> 1 if first string value is greater than second string value
System.out.println(s1.compareTo(s2)); // 0 (same value)
System.out.println(s1.compareTo(s3)); // 1 (lowercase "t" is greater than uppercase "t")
}
}
There are 3 ways to compare strings in Java:
- using equals() method
- using == operator
- using compareTo() method