Grails Cookbook - A collection of tutorials and examples

Java String Compare

Java String is a data structure that's very essential because of it's capability to adapt in many cases. Many programmers do highly recommend utilizing this type of structure alternatively as it is easy to transform from and to other data type. For example, we can convert String to date or numerical value, vice versa. In this post, we will discuss how to compare Strings in Java


Case Insensitive

There is a way to check and compare if two strings are the same regardless of the case sensitive. equalsIgnoreCase is the right method to utilize from the String class. Observe and study the altered program below from the previous sample written above:
public class SampleTest {
    public static void main(String[] args) {
        String stringFirst = "java";
        String stringSecond = "JAVA";
        System.out.println(firstString.equalsIgnoreCase(stringSecond));
    }
}


Case Sensitive

The most common thing we want to do is to compare if the contents of two strings are the same. For this, we can use the method equals from the String class. Consider the code below: Now if the two strings with the same contents are to be compared, we can utilize the equals method as we've partially discussed with the previous post (Java Hashcode). Check out the written example below:
public class SampleTest {
    public static void main(String[] args) {
        String stringFirst = "hello";
        String stringSecond = "world";
        String stringThird = "hello";
        System.out.println(firstString.equals(stringSecond));
        System.out.println(firstString.equals(stringThird));
    }
}
Let's try another comparison approach including case sensitive regarding equals. The program below has two strings with similar value but different case.
public class SampleTest {
    public static void main(String[] args) {
        String stringFirst = "java";
        String stringSecond = "Java";
        System.out.println(firstString.equals(stringSecond));
    }
}


Same String Instance

One situation to consider is not all the time we want to compare the values inside the two strings, but instead we would like to know if the object instance is the same with the other string. Check out the written sample below:
public class SampleTesting {
public static void main(String[] args) {
	String stringFirst = "hello";
	String stringSecond = "he";
	stringSecond=stringSecond+"llo";
	String stringThird = stringFirst;
	System.out.println("The First String is: "+stringFirst);
	System.out.println("The Second String is: "+stringSecond);
	System.out.println("The Third String is: "+stringThird);
	System.out.println(stringFirst == stringSecond);
	System.out.println(stringFirst == stringThird);
    }
}
Another thing that we should be aware of is not all the time there's an assurance that the two strings are different instances just because they are similar. Take a look at the modified program below:
public class SamleTesting {
	public static void main(String[] args) {
	String stringFirst = "hello";
	String stringSecond = "hello";
	String stringThird = stringFirst;
	System.out.println("The First String is: "+stringFirst);
	System.out.println("The Second String is: "+stringSecond);
	System.out.println("The Third String is: "+stringThird);
	System.out.println(stringFirst == stringSecond);
	System.out.println(stringFirst == stringThird);
	}
}
The first and second strings seems different instances at first glance, but this is not what's happening, since the Java Virtual machine holds the idea of String pool, Java is able to reuse that specific instance considering there's an existing instance in the pool already.


Apache Commons StringUtils

Another way to utilize while comparing two strings is the utility class StringUtils that's found in the Apache Commons. Although it's easy to compare strings without a utility, StringUtils is capable of handling nulls better. Check out the written program below:
public class SampleTesting {
    public static void main(String[] args) {
        String string1 = null;
        String string2 = "a";
        System.out.println(string1.equals(string2));
    }
}
This will throw us an exception.
Exception in thread "main" java.lang.NullPointerException
StringUtils method can handle nulls much better just as said before. Now observe the code below:
public class Test {
    public static void main(String[] args) {
        String string1 = null;
        String string2 = "a";
        System.out.println(StringUtils.compare(string1, string2));
    }
}
This is the result of the code:
-1
Under this program, the implementation is the same with this:
public static int compare(final String string1, final String string2) {
    if (string1 == string2) {
        return 0;
    }
    if (string1 == null) {
        return -1;
    }
    if (string2 == null) {
        return 1;
    }
    return string1.compareTo(string2);
}


Less Than, Equal, or Greater Than

There are times that it's necessary to have knowledge if the strings we are comparing is less than the other one, or if the other is greater than the other string, or both strings are just similar. This is the purpose of the method compareTo. Observe the written program below:
public class SampleTesting {
    public static void main(String[] args) {
        System.out.println("abc".compareTo("abc"));
        System.out.println("aaa".compareTo("abc"));
        System.out.println("ccc".compareTo("abc"));
    }
}
compareTo will give you 0 if both strings are equal, a negative number will return if the first string is less than the other and if it's greater than the second string, you will get a positive value. Check out the result below:
0
-1
2
Let's try a different approach for a deeper understanding:
public class SampleTesting {
    public static void main(String[] args) {
        compare("abc", "abc");
        compare("aaa", "abc");
        compare("ccc", "abc");
    }
    private static void compare(String firstString, String secondString) {
        int theResult = firstString.compareTo(secondString);
        if (theResult == 0) {
            System.out.println(firstString + " is equal to " + secondString);
        } else if (theResult < 0) {
            System.out.println(firstString + " is less than " + secondString);
        } else if (theResult > 0) {
            System.out.println(firstString + " is greater than " + secondString);
        }
    }
}
This is the output of the program above:
abc is equal to abc
aaa is less than abc
ccc is greater than abc
Do not forget that the method compareTo is also case sensitive, changing the case of one string will result to a different output. Take a look at the program below:
public class SampleTesting {
    public static void main(String[] args) {
        compare("abc", "abc");
        compare("aaa", "ABC");
        compare("CCC", "abc");
    }
    private static void compare(String firstString, String secondString) {
        int theResult = firstString.compareTo(secondString);
        if (theResult == 0) {
            System.out.println(firstString + " is equal to " + secondString);
        } else if (theResult < 0) {
            System.out.println(firstString + " is less than " + secondString);
        } else if (theResult > 0) {
            System.out.println(firstString + " is greater than " + secondString);
        }
    }
}
The first line is true, but it's the opposite with the rest of the output. This is because we altered the case for the second and third compare.
abc is equal to abc
aaa is greater than ABC
CCC is less than abc
Just like what we did with equalsIgnoreCase, we will now utilize this method with compareTo. There is another option that we can use to ignore case sensitive if we want to compare strings, and that is: compareIgnoreCase.

This is an altered version of the program above, study and observe how the compareIgnoreCase works:

public class SampleTesting {
    public static void main(String[] args) {
        compare("abc", "abc");
        compare("aaa", "ABC");
        compare("CCC", "abc");
    }
    private static void compare(String firstString, String secondString) {
        int theResult = firstString.compareToIgnoreCase(secondString);
        if (theResult == 0) {
            System.out.println(firstString + " is equal to " + secondString);
        } else if (theResult < 0) {
            System.out.println(firstString + " is less than " + secondString);
        } else if (theResult > 0) {
            System.out.println(firstString + " is greater than " + secondString);
        }
    }
}
Just like our discussion a while ago, the compareIgnoreCase took no notice of the case whether if the string is in upper or lowercase.
abc is equal to abc
aaa is less than ABC
CCC is greater than abc