Wednesday, July 6, 2022

How to compare two String in Java - String Comparison Example

String comparison is a common programming task and Java provides several way to compare two String in Java. String is a special class in Java, String is immutable and It’s used a lot in every single Java program starting from simple test to enterprise Java application. In this Java String compare tutorial we will see different ways to compare two String in Java and find out how they compare String and when to use equals() or compareTo() for comparison etc.

Here are four examples of comparing String in Java
1) String comparison using equals method
2) String comparison using equalsIgnoreCase method
2) String comparison using compareTo method
4) String comparison using compareToIgnoreCase method

We will see String compare Example using each of this method in example section, before that let's get some theory:

This article is in continuation of my earlier post on String  like Difference between String and StringBuffer in Java and How to replace String in java using regular expression etc. If you haven’t read them already you may find them useful and worth reading.


Compare two String using equals method in Java

equals()method compare two Strings for content equality. So if two string contains the same letters, in the same order and in some case they will be equals by equals() method. equals() method is defined in Object class and String class overrides that for character-based comparison.

You can also check 5 tips to override equals()method in Java for more details on equals and its implementation. For example for two Strings "Sony" and "Sony", equals() will return true but for "Sony" and "SONY" it will return false.




Compare String using the equalsIgnoreCase method in Java

equalsIgnoreCase is more liberal than equals and compares two strings ignoring their case. So if two String contains the same characters and in the same order despite there case e.g. lower case, upper case, Capital case, or Camel case they will be equal by equalsIgnoreCase.

For example "sony" and "SONY" two Strings will be the same by equalsIgnoreCase and it will return true but "Sony" and "Samsung" will not be the same and it will return false because they don't contain same characters.

How to compare two String in Java - String Comparison Example




Comparing String using compareTo

compareTo is actual comparison method unlike equals()and equalsIgnoreCase() and tell us whether two Strings are lexicographically equal, precedes or follows each other. if you want to sort Strings lexicographically compareTo() method is used. 

This is also called the natural order of String It returns zero if two Strings are same, less than zero if calling string comes before argument string and greater than zero if calling string comes later than argument string as shown in the example below. 

See things to remember while overriding compareTo method in Java for more detail on compareTo method.  



Compare String using compareToIgnoreCase

Similar to compareTo() method with ignoring case like equalsIgnoreCase() and return the same values as returned by compareTo during String comparison.


Don't use "==" for String comparison

String comparison example - compare two strings using equalsMany Java programmer makes the mistake of using "==" for string comparison. "==" just check if two reference variables are pointing two same objects in Java heap and since String is immutable in Java and maintained in String pool two String literal refer same String object which gives the sense that "==" can be used to compare string which is incorrect. always use equals() method for equality check and compare method for actual string comparison.

Another way of comparing String is by writing a custom Comparator in Java. write your comparison logic in compare() method and then you can use that logic to compare two strings.

public class StringComparisonExample {

    public static void main(String args[]) {

        String tv = "Bravia";
        String television = "Bravia";

        // String compare example using equals
        if (tv.equals(television)) {
            System.out.println("Both tv and television contains same letters and equal by equals method of String");
        }

        // String compare example in java using compareTo
        if (tv.compareTo(television) == 0) {
            System.out.println("Both tv and television are equal using compareTo method of String");
        }

        television = "BRAVIA";

        // Java String comparison example using equalsIgnoreCase
        if (tv.equalsIgnoreCase(television)) {
            System.out.println("tv and television are equal by equalsIgnoreCase method of String");
        }

        // String comparison example in java using CompareToIgnoreCase
        if (tv.compareToIgnoreCase(television) == 0) {
            System.out.println("tv and television are same by compareToIgnoreCase of String");
        }

        String sony = "Sony";
        String samsung = "Samsung";

        // lexicographical comparison of String in Java with ComapreTo
        if (sony.compareTo(samsung) > 0) {
            System.out.println("Sony comes after Samsung in lexicographical order");
        } else if (sony.compareTo(samsung) < 0) {
            System.out.println("Sony comes before Samsung in lexicographical order");
        }
    }

}

Output:
Both tv and television contains same letters and equal by equals method of String
Both tv and television are equal using compareTo method of String
tv and television are equal by equalsIgnoreCase method of String
tv and television are the same as compareToIgnoreCase of String
Sony comes after Samsung in lexicographical order


That's all about how to compare two String objects in Java. As I said, there are multiple ways to compare String in Java like using equals(), == operator, compare(), and compareTo() and each has their own special way to implement String objects like == compare memory location of string object while equals() compare content of String. 

These were some common examples of comparing string in Java. Avoid the common mistake of using equality operator “==” for comparing String instead of always use equals() method.


Few more Java tutorials on String you may like

10 comments:

  1. String tv = "sony Bravia";
    String television = "sony is a leading innovative firm and has produced a master peice like Bravia which is ruling todays entertainment world";

    if we observe string TV it contains "sony bravia"
    if we observe String television is contains "sony on the first place and then continued --- had has got "bravia" , so how to do you compare tv with television and we have a condition if only television contains tv then passed else failed

    ReplyDelete
  2. you better use patter matching ... by using regular expression ...

    ReplyDelete
  3. if(array[0].equals(""))
    what the use of quotation ? pls help..

    ReplyDelete
  4. If 2 Strings are intern, then we can use "==" to comapre strings. By default String literal are intern. So we can use "==" to comapre strings.

    ReplyDelete
  5. I see all these methods compare Strings alphabetically, is there any other way to Compare String in Java, which can compare Strings based upon custom logic?

    ReplyDelete
  6. @Test
    public void test(){

    StringBuilder sb = new StringBuilder();
    sb.append("a").append("b");

    String s1 = "ab";
    String s2 = "ab";
    String s3 = sb.toString();

    Assert.assertTrue( s1.equals(s2) ); // passes
    Assert.assertTrue( s1==s2 ); // passes

    Assert.assertTrue( s1.equals(s3) ); // passes
    Assert.assertTrue( s1==s3 ); // fails
    };

    ReplyDelete
  7. ...and the above example can be extended with the following interesting lines:

    final String s4 = s3.intern();

    Assert.assertTrue(s1.equals(s4)); // passes
    Assert.assertTrue(s1 == s4); // passes

    ReplyDelete
  8. Hi there, can you a explain more about why "==" is not good on compare two string whether they are "equals". Because Java is using String pool, which means one string will only have one instance in the pool but have many references. Looks like when using "==" to compare, as long as two string are both reference to the same string in string pool, the value is "equals".

    ReplyDelete
  9. Imagine that you have an application that on a daily basis imports data from some other system and loads data into the data base. On demand the system loads the data, all as strings, into memory and then holds them in memory while it converts some of them to integer or double or date and performs complex calculations on them. Now imagine that you are loading millions of rows when you do this.

    And because you loaded them from the database they are not string literals and not automatically loaded into the string pool therefore even when .equals() returns true == will not.

    If most of your data consists of hundreds of thousands of the same strings, the same date string, or lots of "Y" and "N", or the same string identifiers like unit ids, or the same range of numbers, then it becomes imperative to load these strings so that equal strings refer to the same memory space to cut down as much as possible on memory consumption.

    ReplyDelete