How can compare the Strings in java

Submitted 2 years, 11 months ago
Ticket #432
Views 356
Language/Framework Java
Priority Low
Status Closed

How can compare the Strings in java

Submitted on May 16, 21
add a comment

1 Answer

Verified

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")
  }
}

Submitted 2 years, 10 months ago


Latest Blogs