How to check if two String variables are same in Java? equals(), equalsIgnoreCase() and == operator Example

There are multiple ways to compare two strings alphabetically in Java e.g. == operator, equals() method or compareTo() method, but which one is the best way to check if two strings are equal or not? Programmers often confused between == operator and equals() method, and think that comparing strings using == operator should be faster than equals() method, and end up using that. Though they are not completely wrong, they often missed the point that == operator is designed to compare object equality, not String equality, which is actually defined in equals()method and compare Strings alphabetically. 

When you compare two strings using the == operator, it may or may not return true, especially if you are expecting result based on contents. It will only return true if both reference variables are pointing to the same objects, like in the case of interned string or String literals. Otherwise, it will return false, even if the content of String remain same.

It's one of the coding best practice in Java to use equals() method to check String equality, i.e. to check if two String variable contains same values or not. This method also come with another flavor called equalsIgnoreCase(), which perform case insensitive equality check and should be used to perform case insensitive equality check.

You should always prefer using equalsIgnoreCase() method, in place of converting String case before comparing. Yes, that's true, I have seen code, where developer first convert case e.g. in uppercase or lowercase before comparing String for equality to avoid any issue with case sensitivity, that is not the right way, because it will generate lots of temporary String object, which may fill up your permgen space and result in java.lang.OutOfMemoryError:PermGen Space

Since size of permgen is lot less than size of heap, by default it’s 64MB to 92MB depending upon platform, JVM version and mode, you want to be careful with String object which belongs to String pool, which is located in permgen space. 

One more thing which is worth noting regarding this point is that, since String is immutable and final in Java, any modification e.g. calling toUppercase() or toLowercase() will return a different String object. In short always prefer equalsIgnoreCase() instead of manually converting strings into same case for comparison.




String Equality check Example

Now that you know, best way to check if two Strings are equal or not is by using equals() and equalsIgnoreCase() method, let's see couple of examples of using these methods, and how it is different than traditional == operator. By the way you can also read difference  between == and equals in Java, to learn much more detailed comparison.

/**
 * Always use equals() and equalsIgnoreCase() method to compare two Strings in Java
 * @author Javin Paul
 */
public class StringComparator {

    public static void main(String args[]) {
     
        String literal = "abc";
        String object = new String(literal);
      
        // comparing Strings using equals() method
        if(literal.equals(object)){
            System.out.printf("String %s and %s are equal %n", literal, object);
        }else {
            System.out.printf("String %s and %s are not equal %n", literal, object);
        }
       
        // comparing String using == Equality operator
        if(literal == object){
            System.out.printf("String %s and %s are same object %n", literal, object);
        }else {
            System.out.printf("String %s and %s are  different object %n", literal, object);
        }
    }    
  
}

Output
String abc and abc are equal
String abc and abc are  different object

If you are truly comparing Strings alphabetically to arrange them in order, use compareTo() method from Comparable interface in Java. It also compare String based upon there value, and can be used to sort String alphabetically, if they are stored in List using Collections.sort() method. 

If you are checking String equality, always prefer equals() and equalsIgnoreCase() depending upon case sensitive or insensitive equality check.




Best Practices to Compare String Objects in Java

Since String is widely used in any Java program, following any String related best practice result in good quality code and improves stability, performance and robustness of Java applications. Based upon usage of String objects and there frequent comparison to other Strings, following best practices will certainly help.

1. Call equals() on known string object

While comparing two Strings, always call equals() method on String object, which is either literal or not null. Because calling equals() on null will throw java.lang.NullPointerException, but comparing a not null String  with a null String will return false, as shown in the following example :

String apple = "Apple";
String fruit = getFruit(); // can be null or any fruit or apple

// This code will break if fruit is null
if(fruit.equals("Apple"){
  System.out.println("Make Apple Shake");
}

// This code will work even if fruit is null
if("Apple".equals(fruit){
  System.out.println("Make Apple Shake");
}

This is just one of the few tricks to avoid NullPointerException in Java, but it result in immense improvement in stability. It's also worth knowing that, while comparing String will null, it's better to use == operator than equals() method e.g.

if(fruit != null){
  System.out.printf("We have got %s today", fruit.name());
}

If you call fruit.equals(null), you risk yourself to another NullPointerException, as fruit can also be null.


How to compare String variables in Java? equals(), equalsIgnoreCase() and == operator Example


That's it on my best way to compare Strings alphabetically in Java. As I said, use equals() and equalsIgnoreCase() for checking equality, use them correctly to avoid java.lang.NullPointerException and use compareTo() method to arrange multiple strings in a particular order e.g. ascending and descending order lexicographically. Don't compare two strings using == operator, except for null check, which you should try to minimize by following best practices like null object pattern.


Related Java String tutorials for beginners


1 comment:

  1. If you ask me, comparing with == operator is always fastest way of comparing two Strings. If you have only literals and all your Strings are interned, you can take advantage of speed offered by equals operator than slow equals() method.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.