Very big waterfall

How to compare two strings in Java

This tutorial may be helpful if you need to compare two strings in the Java programming language. This is a very simple task. You just have to use a special method that will check if the string values are equal. However, the Java language provides many different methods that can be used for that purpose.

As a result, this guide contains a list of the most popular methods that allow you to compare two strings. You can test each option and choose a solution that is suitable for your code.

Using the String.equals() method

The Java language provides the String class that can hold string values. Also, there is an equals() method that allows you to compare the current string with the value given in a parameter. The comparison is case sensitive, which means that, for example, the green and Green words are not equal.

We've created a very simple application that demonstrates how you can compare two strings using the equals() function. Please review our code sample below.

class sample {
    public static void main(String args[]) {
        String colorName1 = "Green";
        String colorName2 = "Blue";
        String colorName3 = "Red";
        String colorName4 = "Green";

        System.out.println(colorName1.equals(colorName1));
        System.out.println(colorName1.equals(colorName2));
        System.out.println(colorName1.equals(colorName3));
        System.out.println(colorName1.equals(colorName4));
    }
}

As you see, the "colorName1" variable is compared to the other values and the result is printed to the standard console. If you run the given code, it should produce the result like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
true
false
false
true

The first result is true, that's because we compare the string to itself. The last result is also true, because two different variables contain the same value, which is the word "Green".

Using the String.equalsIgnoreCase() function

If for some reason you need the case insensitive comparison, then it's not an issue. The String class also provides the equalsIgnoreCase() method that allows you to check if strings are equal even if some letters are in a different case.

The usage of that method is the same as we've described in the previous section of this tutorial. You just have to pass a single argument to the equalsIgnoreCase() function. Please see our code sample below.

class sample {
    public static void main(String args[]) {
        String colorName1 = "Green";
        String colorName2 = "green";
        String colorName3 = "Blue";
        String colorName4 = "Red";

        System.out.println(colorName1.equalsIgnoreCase(colorName1));
        System.out.println(colorName1.equalsIgnoreCase(colorName2));
        System.out.println(colorName1.equalsIgnoreCase(colorName3));
        System.out.println(colorName1.equalsIgnoreCase(colorName4));
    }
}

Now, you can try to run the given code in the terminal. The output should be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
true
true
false
false

As you may see, the first call to the equalsIgnoreCase() method returned the true value. That is because the string equals itself. The second call returns the true value as well because the words green and Green are the same if we use the case insensitive comparison. The last two results are false because the strings are completely different.

Using the String.compareTo() method

You may also use the compareTo() method to compare the string values. The difference is that this method will return an integer value. If the strings are equal, the result will be zero. A negative number is returned if the string is less than the other value. And a positive number is returned if the current string is greater than the other string.

Please see the code sample below.

class sample {
    public static void main(String args[]) {
        String colorName1 = "Green";
        String colorName2 = "Blue";
        String colorName3 = "Red";
        String colorName4 = "Green";

        System.out.println(colorName1.compareTo(colorName1));
        System.out.println(colorName1.compareTo(colorName2));
        System.out.println(colorName1.compareTo(colorName3));
        System.out.println(colorName1.compareTo(colorName4));
    }
}

As you see, the usage of the compareTo() method is very simple. If you run the given code, the console may have an output like the given below. You may notice that there are numbers instead of false or true values.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
0
5
-11
0

Using the String.compareToIgnoreCase() method

The compareToIgnoreCase() method allows you to compare string values in case-insensitive manner. It's similar to the previous method and returns the integer value. If the result is zero, the strings are equal. However, if the returned number is negative, then the value is less than the other string. But the positive number means that the string is greater than the other value.

Please see the following code that shows how this method works.

class sample {
    public static void main(String args[]) {
        String colorName1 = "Green";
        String colorName2 = "green";
        String colorName3 = "Blue";
        String colorName4 = "Red";

        System.out.println(colorName1.compareToIgnoreCase(colorName1));
        System.out.println(colorName1.compareToIgnoreCase(colorName2));
        System.out.println(colorName1.compareToIgnoreCase(colorName3));
        System.out.println(colorName1.compareToIgnoreCase(colorName4));
    }
}

The console output will contain numbers if you run the given code. Please see the example below.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
0
0
5
-11

Using the String.contentEquals() method

If you need to compare a string value to the string buffer, then Java may also help you. The String class provides a special contentEquals() method. It accepts a single parameter that can be either CharSequence or StringBuffer.

Please see the following code. There you can see how the string is compared to the string buffer.

class sample {
    public static void main(String args[]) {
        String colorName = "Green";

        StringBuffer colorNameBuffer1 = new StringBuffer("Blue");
        StringBuffer colorNameBuffer2 = new StringBuffer("Red");
        StringBuffer colorNameBuffer3 = new StringBuffer("Green");

        System.out.println(colorName.contentEquals(colorNameBuffer1));
        System.out.println(colorName.contentEquals(colorNameBuffer2));
        System.out.println(colorName.contentEquals(colorNameBuffer3));
    }
}

The console should have output like the following. The last result is true because a value in the buffer equals the string.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
false
false
true

Using the Objects.equals() method

The Objects class provides the equals() method that you can also use to compare two string values. This method is static and accepts two parameters.

Following is the example that shows how to use this method. Please pay attention that we also have to add the import keyword there. It allows us to use the Objects class in the project.

import java.util.Objects;

class sample {
    public static void main(String args[]) {
        String colorName1 = "Green";
        String colorName2 = "Blue";
        String colorName3 = "Red";
        String colorName4 = "Green";

        System.out.println(Objects.equals(colorName1, colorName1));
        System.out.println(Objects.equals(colorName1, colorName2));
        System.out.println(Objects.equals(colorName1, colorName3));
        System.out.println(Objects.equals(colorName1, colorName4));
    }
}

It is worth mentioning that if each parameter is null then the equals() method will return the true value. If one parameter points to an object and the other parameter is null, then the result will be false.

Otherwise, if all parameters are valid objects, then this method will call the equals() method of the first value. In our case, the first parameter is a string, which means that the regular string comparison will be used to determine if the values are equal.

Below, you can see the console output of the given code.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
true
false
false
true

Comparing a string with a constant value

There is a very nice feature in the Java language that can simplify the code. You may directly compare a constant value with the other string by using the equals() method. Please see our code sample below.

class sample {
    public static void main(String args[]) {
        String colorName1 = "Green";
        String colorName2 = "Blue";
        String colorName3 = "Red";
        String colorName4 = "Green";

        System.out.println("Green".equals(colorName1));
        System.out.println("Green".equals(colorName2));
        System.out.println("Green".equals(colorName3));
        System.out.println("Green".equals(colorName4));
    }
}

If you run the given code, the console output should be like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
true
false
false
true

Using the == operator

You may want to use the regular == operator to compare the string values. How this method may not work as expected and the code may have various issues.

The == operator compares references to the objects, but not the values. It means that the result will be true if both variables point to the same object in memory.

Please see the following sample, it demonstrates how exactly the == operator works in a code.

class sample {
    public static void main(String args[]) {
        String colorName1 = "Green";
        String colorName2 = "Blue";
        String colorName3 = "Green";
        String colorName4 = new String("Green");

        if (colorName1 == colorName1) {
            System.out.println("values are equal");
        } else {
            System.out.println("values are not equal");
        }

        if (colorName1 == colorName2) {
            System.out.println("values are equal");
        } else {
            System.out.println("values are not equal");
        }

        if (colorName1 == colorName3) {
            System.out.println("values are equal");
        } else {
            System.out.println("values are not equal");
        }

        if (colorName1 == colorName4) {
            System.out.println("values are equal");
        } else {
            System.out.println("values are not equal");
        }
    }
}

The first comparison will return true because we compare the object to itself. The second comparison will return false because the objects and the values are different.

However, the third result will produce the true value even if we compare the different objects. That's because Java optimizes the code and the same string variable is assigned to the different variables.

But, in a fourth case, you may see that we instantiate a new object with help of the new operator. If that code is executed, the == operator will return false because two different objects are compared to each other.

Please see the following console output. It demonstrates how exactly the == operator works.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
values are equal
values are not equal
values are equal
values are not equal

Making your own custom function to compare two strings

In most cases, you may want to use the standard Java methods to compare the string values. However, you may also be curious on how to make a custom string comparison code.

The following sample contains the MyTools class that provides the static stringsAreEqual() method. At the beginning, we compare the length of the strings there. If those values are different, then the false value is returned.

After that, we use the for loop to compare each character in the first string with the character in the other string at the same position. If the values are different, then the false result is returned.

class MyTools {
    public static boolean stringsAreEqual(String value1, String value2) {
        int value1Length = value1.length();
        int value2Length = value2.length();

        if (value1Length != value2Length) {
            return false;
        }

        for (int index = 0; index < value1Length; index++) {
            if ((int)value1.charAt(index) != (int)value2.charAt(index)) {
                return false;
            }
        }

        return true;
    }
}

class sample {
    public static void main(String args[]) {
        String colorName1 = "Green";
        String colorName2 = "Blue";
        String colorName3 = "Red";
        String colorName4 = "Green";

        System.out.println(MyTools.stringsAreEqual(colorName1, colorName1));
        System.out.println(MyTools.stringsAreEqual(colorName1, colorName2));
        System.out.println(MyTools.stringsAreEqual(colorName1, colorName3));
        System.out.println(MyTools.stringsAreEqual(colorName1, colorName4));
    }
}

Now, you can try to run the given code in a console. The console should have an output like the following.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
true
false
false
true

Using the switch statement

This method of comparing string values is unusual. However, you may also consider using it in your project. If there is a predefined list of options, you can use the switch statement. It allows you to write a code that will be executed if some constant equals the given value.

Please see the following code sample.

class sample {
    public static void main(String args[])
    {
        String defaultColorName = "Green";

        switch (defaultColorName) {
            case "Green": {
                System.out.println("Green");
                break;
            }

            case "Blue": {
                System.out.println("Blue");
                break;
            }

            case "Red": {
                System.out.println("Red");
                break;
            }

            default: {
                System.out.println("No color");
                break;
            }
        }
    }
}

If you try to run the given code, it should output Green value to the console.

developer@developer-pc:~/samples/java$ javac ./sample.java && java sample
Green

Conclusion

The Java programming language provides many various options that you can use to compare string values. For a simple case, there is a String.equals() method. It returns the boolean value, which may be either true or false, depending on a comparison result.

If you need to know how exactly the strings are different, you may use the String.compareTo() method that returns an integer value.

Also, there are special methods that allow you to compare the string values in a case insensitive manner. It can be helpful in various situations. For example, you are comparing the data from different sources and not sure that the strings are in the correct case.

Related Articles

Defocused lights

How to sort arrays in Java

Gray and brown mountain

Converting byte array to string and vice versa in Java

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *