Low Orbit Flux Logo 2 D

Java How To Compare Strings

Comparing strings in Java is easy. You do need to be a bit careful though. You need to be aware of what you are comparing. You can compare the content of a string or the actual string object. Comparing the string object will just tell you if the two Strings are a reference to the same object.

Quick Answer: To compare the value of two strings in Java, use the following:


Most likely, you want to compare the value of two strings. This is pretty easy. You can do this with the equals() method. Note that you can also use the equalsIgnoreCase() method if you want to do a case insensitive comparison.

class Test1 {
    public static void main( String args[] ) {

        String s1 = "abc";
        String s2 = "abc";
        String s3 = "ABC";
        String s4 = "xyz";

        System.out.println(s1.equals(s2));            // true
        System.out.println(s1.equals(s3));            // false
        System.out.println(s1.equalsIgnoreCase(s3));  // true
        System.out.println(s1.equals(s4));            // false


The first comparison is true because the values are the same. The second is false because the characters are a different case. The third comparison is true because we ignore case. The fourth comparison is false because the strings are completely different.

You can also compare using the == operator or the compareTo() method but we aren’t going to cover those here.