Thursday, March 29, 2012

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  e.g. 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

String comparison example - compare two strings using equalsequals()method compare two Strings for content equality. So if two string contains same letters, in same order and in same case they will be equals by equals() method. equals() method is defined in Object class and String class overrides that for character based comparison. 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 equalsIgnoreCase method in Java

equalsIgnoreCase is more liberal than equals and compare two strings ignoring there case. So if two String contains same characters and in same order despite of 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 same by equalsIgnoreCase and it will return true but "Sony" and "Samsung" will not be same and it will return false because they don't contain same characters.


Comparing String using compareTo

compareTo are 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 natural order of String.   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 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 same values as returned by compareTo during String comparison.


Don't use "==" for String comparison

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

Another way of comparing String is writing custom Comparator in Java. write your comparison logic in compare() method and than 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 same by compareToIgnoreCase of String
Sony comes after Samsung in lexicographical order


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

Few more Java tutorials on String you may like


7 comments :

Madhusudhan Konduru said...

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

Bikash Mazumdar said...

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

user said...

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

Anonymous said...

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.

Grame said...

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?

Zoltán said...

@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
};

Zoltán said...

...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

Post a Comment