How to compare two Strings in Java

Methods to Compare Strings in Java

Java provides different methods you can leverage to compare two strings in Java. String comparison in Java is a feature that matches a sequence of characters to a string.

To learn how to compare strings in Java, you can use the methods provided by the following classes.

  • String class from the Java.lang package.
  • Objects class from the Java.util package.
  • StringUtils class from the org.apache.commons.lang3 package.

Most of these Java compare strings methods have solutions for ignoring the case. In this Java tutorial, you will learn the different methods that you can use to compare two strings.

Method 1: String equals() method

The Java String equals() method compares two string objects for equal string values.

Syntax:

public boolean equals(Object anObject)

equals() method parameters:

anObject – The argument string for comparing strings.

equals() method return types

  • Returns true if the string literal provided is the same as the first string.
  • Returns false if the first string is not the same as the argument string.

Example:

public class CompareTwoStrings {
 public static void main(String[] args) {
   String stringOne = "Guru99";
   String stringTwo = "Guru99";
   System.out.println("is Guru99 equal to Guru99: "+stringOne.equals(stringTwo));
   String stringThree = "GURU99";
   System.out.println("is Guru99 equal to GURU99: "+stringOne.equals(stringThree));
  }
}

Expected Output:

is Guru99 equal to Guru99: true
is Guru99 equal to GURU99: false

Explanation:

  • You got false in the last output because the specified object has a different case.

Note: Use the string equals method for case-sensitive string comparison. Use the “equalsIgnoreCase” method to compare string objects with different string values.

Method 2: Objects equals() method

The Java Objects equals() method compares two string objects to find if they have the same values.

Syntax:

public static boolean equals(Object a, Object b)

equals() method parameters

a – Argument string for the first string object.

b – Argument string for the second string object.

equals() method return types

  • Returns true if the string literals are equal. Passing a null value in the two arguments will also return true.
  • Returns false if the string literals are not equal.

Example:

import java.util.Objects;
public class CompareTwoStrings {
    public static void main(String[] args) {
        String stringOne = "Guru99";
        String stringTwo = "Guru99";
        System.out.println("is Guru99 equal to Guru99: " + Objects.equals(stringOne, stringTwo));
        String stringThree = null;
        String stringFour = null;
        System.out.println("is Guru99 equal to Guru99: " + Objects.equals(stringThree, stringFour));
    }
}

Output:

is Guru99 equal to Guru99: true
is Guru99 equal to Guru99: true

Explanation:

From this example, you can see that the output is a boolean value of true since the strings compared are equal.

Method 3: String compareTo() method

The Java String compareTo() method compares two strings in alphabetic order. It is usually referred to as lexicographic order.

Syntax:

public int compareTo(String str)

compareTo() method parameters

str – The string to compare against the current string.

compareTo() method returns

  • 0 – Returns zero if the specified object is equal to the current string.
  • < 0 – Returns a number less than zero if this string is less than the specified object.
  • > 0 – Returns a number greater than zero if this string exceeds the provided string.

Example:

public class CompareTwoStrings {
    public static void main(String[] args) {
        String stringOne = "Guru99";
        String stringTwo = "Guru99";
        System.out.println("is Guru99 equal to Guru99: " + stringOne.compareTo(stringTwo));
        String stringThree = "GURU99";
		// u = 117, U = 85, result = 117-85 = 32
        System.out.println("is Guru99 equal to GURU99: " + stringOne.compareTo(stringThree));
    }
}

Expected Output:

is Guru99 equal to Guru99: 0
is Guru99 equal to GURU99: 32

Explanation:

The first result returns a value of zero since the first and second strings are equal.

The second result returns a value of thirty-two since the characters are different.

Note: To ignore the cases, you can use the “compareToIgnoreCase” method.

Method 4: StringUtils equals() method

The Java StringUtils equals() method compares the equality of two sequences of characters.

Ensure you have added the “org.apache.commons.lang3” library in your program. This will allow you to compare strings using the StringUtil methods.

For Maven projects, use this guide to add the library to the project.

However, If you want to add the library without any build tools, use this guide.

Syntax:

public static boolean equals(CharSequnce cs1, CharSequence cs2)

StringUtils equals() method parameters

  • cs1 – A sequence of characters for the first argument.
  • cs2 – A sequence of characters for the second argument.

StringUtils equals() method returns

  • Returns true if the string comparison is equal. It applies if you pass a null value in the two arguments.
  • Returns false if the string comparison is not equal.

Example:

import org.apache.commons.lang3.StringUtils;
public class CompareTwoStrings {
    public static void main(String[] args) {
        String stringOne = "Guru99";
        String stringTwo = "Guru99";
        System.out.println("is Guru99 equal to Guru99: " + StringUtils.equals(stringOne, stringTwo));
        String stringThree = "GURU99";
        System.out.println("is Guru99 equal to GURU99: " + StringUtils.equals(stringOne, stringThree));
    }
}

Output:

is Guru99 equal to Guru99: true
is Guru99 equal to GURU99: false

Explanation:

Since the contents of the first and second strings are equal, the result returns true.

You can use the “equalsIgnoreCase” method to ignore the case.

Method 5: StringUtils equalsAny() method

The Java StringUtils equalsAny() method checks if a string exists in the arguments.

Syntax:

public static boolean equalsAny(CharSequence string, Charsequence… searchStrings)

StringUtils equalsAny() method parameters

  • string – The string value for the first argument. The argument can also have a null value.
  • searchStrings – A set of string arguments for the method to find if the first argument string is present.

StringUtils equalsAny() method returns

  • Returns true if the string to match exists in the variable number of search strings. This applies if both of the arguments are null.
  • Returns false if the string to match does not match any string in the variable number of search strings.

Example:

import org.apache.commons.lang3.StringUtils;
public class CompareTwoStrings {
    public static void main(String[] args) {
        String stringOne = "Guru99";
        String[] stringTwo = new String[] {
            "Guru99",
            "JavaGuru99"
        };
        System.out.println("is Guru99 available: " +
            StringUtils.equalsAny(stringOne, stringTwo));
        String[] stringThree = new String[] {
            "GURU99",
            "JavaGuru99"
        };
        System.out.println("is GURU99 available: " +
            StringUtils.equalsAny(stringOne, stringThree));
    }
}

Output:

is Guru99 available: true
is GURU99 available: false

Explanation:

Since the contents of the first string and the second string are equal, the result returns true. You can use the “equalsAnyIgnoreCase” method to ignore the case.

Method 6: Using == operator

The == operator on strings checks if object references have the same address.

Example:

public class CompareTwoStrings {
    public static void main(String[] args) {
        String stringOne = "Guru99";
        String stringTwo = "Guru99";
        System.out.println("is Guru99 == to Guru99: " + (stringOne == stringTwo));
        String stringThree = "GURU99";
        System.out.println("is Guru99 == to GURU99: " + (stringOne == stringThree));
    }
}

Expected Output:

is Guru99 == to Guru99: true
is Guru99 == to GURU99: false

Explanation:

  • The first result returns a boolean value of true. Strings with the same contents get added to the same string pool hence the string share one address.
  • The second result returns a boolean value of false. The objects have different contents, which result in other string pools. This means that the strings have separate object references; thus the output is false.

Method 7: Creating a custom method to Compare two Strings in Java

Create a method that compares two strings using lexicographic order.

Syntax:

public static int compareTwoStrings(String str1, String str2)

Custom method parameters

  • str1 – The string to compare.
  • str2 – The string to compare against.

Custom method returns

  • 0 – Returns zero if the first string is equal to the second string.
  • < 0 – Returns a number less than zero if the first string is less than the second string.
  • > 0 – Returns a number greater than zero if the first string is greater than the second string.

Example:

public class CompareTwoStrings {
    public static int compareTwoStrings(String stringOne, String stringTwo) {
        int lengthOfStringOne = stringOne.length();
        int lengthOfStringTwo = stringTwo.length();
        int minStringLength = Math.min(lengthOfStringOne, lengthOfStringTwo);
        for (int i = 0; i < minStringLength; i++) {
            char stringOneCharValue = stringOne.charAt(i);
            char stringTwoCharValue = stringTwo.charAt(i);
            if (stringOneCharValue != stringTwoCharValue) {
                return stringOneCharValue - stringTwoCharValue;
            }
        }
        if (lengthOfStringOne != lengthOfStringTwo) {
            return lengthOfStringOne - lengthOfStringTwo;
        } else {
            return 0;
        }
    }
    public static void main(String[] args) {
        String stringOne = "Guru99";
        String stringTwo = "Guru99";
        System.out.println("is Guru99 equal to Guru99: " + compareTwoStrings(stringOne, stringTwo));
    }
}

Expected Output:

is Guru99 equal to Guru99: 0

Explanation:

The result returned a value of zero, meaning the custom function is working as expected.

Summary:

The Java compare two strings method to use depends on the following factors.

  • Desire to have control over your method. In this case, create a custom method.
  • You can’t use Legacy code. with Java 6 and lower.
  • The method that has optimal performance.
  • The type of data you are working with. For example, matching a string from a set of variable arguments.
  • The features provided by the outsourced library. For example, the StringUtils library provides varying methods to compare strings.