How to compare strings in Java

In Java, we use equals() to compare string value.


	String str1 = "apple";

	// compare strings case-sensitive
	if (str1.equals("apple")) {
	    System.out.println("I have an apple.");
	}

	String str2 = "apple";
	
	// compare strings case-insensitive
	if (str2.equalsIgnoreCase("APPLE")) {
	    System.out.println("I have an APPLE.");
	}

Output

Terminal

I have an apple.
I have an APPLE.

In this article, we will show you a few ways to compare strings in Java.

Table of contents:

1. Using equals(), compare strings case-sensitive

1.1 In Java, we can use .equals() to compare strings.

StringCompare1.java

package com.mkyong.string.compare;

public class StringCompareEquals {

    public static void main(String[] args) {

        String str1 = "apple";

        boolean result = str1.equals("apple");

        System.out.println(result); // true

    }

}

Output

Terminal

true

1.2 The .equals() is case-sensitive in string comparison.

StringCompare12.java

package com.mkyong.string.compare;

public class StringCompareEquals2 {

    public static void main(String[] args) {

        String str1 = "apple";

        boolean result = str1.equals("Apple");

        System.out.println(result); // false

    }

}

Output

Terminal

false

2. Using equalsIgnoreCase(), compare strings case-insensitive

2.1 Below example uses .equalsIgnoreCase() to compare strings, ignore case, case-insensitive.

StringCompareEqualsIgnoreCase.java

package com.mkyong.string.compare;

public class StringCompareEqualsIgnoreCase {

    public static void main(String[] args) {

        String str1 = "apple";

        boolean result = str1.equalsIgnoreCase("Apple");

        System.out.println(result);    // true

    }

}

Output

Terminal

true  

3. Handle null in strings comparison

3.1 If we use .equals to compare string with a null value, it throws NullPointerException.

StringCompareNull.java

package com.mkyong.string;

public class StringCompareNull {

    public static void main(String[] args) {

        String str1 = null;

        if (str1.equals("hello")) {
            System.out.println("equals");
        }

    }

}

Output

Terminal

Exception in thread "main" java.lang.NullPointerException:
	Cannot invoke "String.equals(Object)" because "str1" is null

3.2 To fix it, check the null before compare strings.

StringCompareNull.java

package com.mkyong.string;

public class StringCompareNull {

    public static void main(String[] args) {

        String str1 = null;

        if (str1 != null && str1.equals("hello")) {
            System.out.println("equals");
        }

    }

}

4. Using contentEquals(), compare strings for CharSequence

  • The .equals() can compare string value only if the object is an instance of String.class.
  • The contentEquals() can compare string value to any CharSequence implementations like StringBuffer or StringBuilder.
StringCompareContentEquals.java

package com.mkyong.string.compare;

public class StringCompareContentEquals {

    public static void main(String[] args) {

        String str1 = "apple";
        String str2 = "apple";
        StringBuilder sb = new StringBuilder("apple");
        StringBuffer buffer = new StringBuffer("apple");

        // true
        System.out.println(str1.equals(str2));
        // false, .equals cant compare StringBuilder
        System.out.println(str1.equals(sb));

        // .contentEquals supports CharSequence
        // CharSequence implementations: StringBuffer, StringBuilder, String, etc.
        // true
        System.out.println(str1.contentEquals(sb));
        // true
        System.out.println(str1.contentEquals(buffer));

    }

}

Output

Terminal

true
false
true
true

5. Using compareTo(), compare strings lexicographically

In Java, we can use compareTo() method compares two strings lexicographically (alphabetical order). It returns a positive number, negative number, or zero.


	s1.compareTo(s2)

	// for example
	"a".compareTo("b")
  • if s1 < s2, it returns negative number.
  • if s1 > s2, it returns positive number.
  • if s1 == s2, it returns 0.

	System.out.println("a".compareTo("b")); // -1
	System.out.println("a".compareTo("c")); // -2

	System.out.println("1".compareTo("2")); // -1
	System.out.println("1".compareTo("3")); // -2

	System.out.println("b".compareTo("a")); // 1
	System.out.println("c".compareTo("a")); // 2

	System.out.println("2".compareTo("1")); // 1
	System.out.println("3".compareTo("1")); // 2

	System.out.println("a".compareTo("a")); // 0
	System.out.println("1".compareTo("1")); // 0

Note
More Java String compareTo() examples.

6. Using Objects.equals() to compare strings

Since Java 1.7 and later, we can use Objects.equals() to ensure both objects are equal, and it works for String.class as well.

StringCompareObjectsEquals.java

package com.mkyong.string.compare;

import java.util.Objects;

public class StringCompareObjectsEquals {

    public static void main(String[] args) {

        String str1 = "apple";
        String str2 = "banana";

        // false
        System.out.println(Objects.equals(str1, str2));

        // true
        System.out.println(Objects.equals(str1, new String("apple")));

        // false
        System.out.println(Objects.equals(null, str2));

        // false
        System.out.println(Objects.equals(str1, null));

        // true
        System.out.println(Objects.equals(null, null));

    }

}

Output

Terminal

false
true
false
false
true

7. Why “==” sometimes work to compare strings?

Why below == operator return true for string comparison, are we supposed to use .equals() to compare strings?


	String str1 = "apple";
	String str2 = "apple";

	// true, why true? why we can use == to compare strings?
	System.out.println(str1 == str2);  

To answer the above question, we need to understand how String interning works in Java.

7.1 String interning, how it works?

In Java, String interning is a method of storing only one copy of each distinct string value into a String intern pool, String constant pool, or String pool. The entire JVM shares a single String pool.

In Java, if JVM sees String literal like below:


	// String literal
	String str1 = "apple";

String interning process starts and decides the following two tasks:

  • If the String pool contains this string, then the string from the pool is returned.
  • If the String pool does not contain this string, add it to the pool, and return a reference to this String object.

Read code comments to understand how to String interning works in Java.


	// JVM checks if this string exists in the string pool? The answer is NO.
	// JVM add this string object to the string pool and returns a reference
	// str1 has a reference "111" (example), which points to "apple" in the string pool
	String str1 = "apple";

	// JVM checks if this string exists in string pool? The answer is YES.
	// JVM returns the reference "111", which points to "apple"
	String str2 = "apple";

	// Now str1 and str2 both have the same reference "111" to the "apple"
	// and that is why it return true here.
	System.out.println(str1 == str2);  

	// move on for the following example

	// JVM see "new", ignore string pool and create a new reference or address "222" (example)
	String str3 = new String("apple");

	// str = address "111"
	// str3 = address "222"

	// false
	System.out.println(str1 == str3);


	// move on for the following example

	// we can use `intern` to add this to the string pool
	// JVM see this "apple" already existed in the string pool
	// JVM returns the reference "111" to str4
	String str4 = str3.intern();

	// true
	System.out.println(str1 == str4);

	// still false, str3 is still has the reference "222"
	System.out.println(str1 == str3);

7.2 Why String interning?

String interning speeds up string comparisons without examining every character of both. Read this Wikipedia – String interning.

8. Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-string

9. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments