Java is an object-oriented programming language that can be used to develop desktop applications, web applications, android applications, games, database connections, etc. In this article, we are going to study how to compare strings in Java. In java, a String is a data type or an object that is used to store text. The string object contains characters that are enclosed by double-quotes.
Example:
package stringcomparison; public class StringComparison { public static void main(String[] args) { String greetings = "Good Morning Java Developers"; System.out.println(greetings); } }
Output:
Good Morning Java Developers
Package StringComparison – stringcomparison is the name of the package. In Java, a package is like a folder that holds multiple related java classes.
Public Class StringComparison – StringComparison, marks the class name. A class in java is a blueprint where objects are created. Public is the class modifier, which means that the class can be accessed from anywhere within the class, within the package, and outside the package.
Public Static Void main(String[] args) – shows java main method. Public is an access modifier that allows the main method to be accessed everywhere. String[] args is an array of a sequence of characters. Static means there is only one occurrence of the main method, and void is an empty return type.
System.out.println() – it’s a method in java that is used to output lines of text.
With that said, we know the basic syntax of a java class. Let’s briefly discuss how to get started up to the stage of comparing strings in java.
Getting started with Java
To get started with Java, you need to have java installed on your pc. Check if Java is installed on your computer, press Windows+Ropen and type cmd to open the command prompt. Then type the following command. “java -version.” Depending on the java version you have, it will show you the following window.
If you have not installed java yet, you can download it here at oracle.com, check on the versions available and download a version based on your operating system. I also recommend you download any of these java integrated development environments; NetBeans, Eclipse, or IntelliJ IDEA.
String Comparison in Java
Let’s now dig in into comparing strings. This can be advantageous when building Java applications; let’s take, for example, building a restaurant food delivery app in java that checks who ordered a particular type of food. You may want to compare your customer’s names with the ones on file.
There are 3 different ways to compare strings in java, which can be important during authentication, sorting, or reference matching. They include:
- String compare by using equals () and equalsIgnoreCase() methods – performs equality check comparison.
- String compare by using compareTo() and compareToIgnoreCase() method. – performs ordering comparison
- String compare by using (==) Operator (equality operator) – performs referenced equality comparison only.
String compare using (==) operator
The equality operator compares if two strings are the same. For them to be considered as the same, they must refer to the same memory allocation. If one has extra space, they cannot be referred to be the same.
Example:
public class StringComparison { public static void main(String[] args) { String first_name = "codeunderscored"; String last_name = "codeunderscored"; if (first_name == last_name) { System.out.println("The First Name matches the Last Name."); } else { System.out.println("The First Name does not match the Last Name."); } } }
Output:
run:
The First Name matches the Last Name.
BUILD SUCCESSFUL (total time: 1 second)
In the code above, the == operator uses the if statement checks if the values of the string first_name and last_name are equal and report back. If they are equivalent, it prints the first statement; else, it prints the second statement.
We do not use the == operator mostly to compare strings because it performs reference equality check only. By this, I mean you cannot use the == operator to compare string objects. Instead, if you compare two string objects, the program will see them differently even if they have the same value. Let’s look at this using an example:
package stringcomparison; public class StringComparison { public static void main(String[] args) { String first_name = new String ("moses"); String last_name = new String ("moses"); if (first_name == last_name) { System.out.println("The First Name matches the Last Name."); } else { System.out.println("The First Name does not match the Last Name."); } } }
Output:
run:
The First Name does not match the Last Name.
BUILD SUCCESSFUL (total time: 0 seconds)
In the example above, we have created two new objects of the String() method. Despite assigning the same value to both the string objects, the program treats them differently and outputs them as they do not match. This is because the program compares the object themselves rather than comparing the value of the strings.
String compare by using equals () and equalsIgnoreCase() methods.
Using equals() method.
We use equals() method when we want to check if the string objects have the same characters and in the same sequence. String equals() method is case sensitive; hence it will return false if the values been compared are of the different case despite being of the same characters and same sequence.
Example 1:
package stringcomparison; public class StringComparison { public static void main(String[] args) { String first_name = new String ("codeunderscored"); String last_name = new String ("codeunderscored"); String name1 = "codeunderscored"; String name2 = "codeunderscored"; if (first_name.equals(last_name)) { System.out.println("The First Name matches the Last Name."); } else { System.out.println("The First Name does not match the Last Name."); } if (name1.equals(name2)) { System.out.println("The First Name matches the Last Name."); } else { System.out.println("The First Name does not match the Last Name."); } } }
Output:
run:
The First Name matches the Last Name.
The First Name matches the Last Name.
BUILD SUCCESSFUL (total time: 1 second)
It’s a clear output that the equals() method can be used to compare both reference equality and string objects.
Example 2:
public class StringComparison { public static void main(String[] args) { String first_name = new String ("codeunderscored"); String last_name = new String ("Codeunderscored"); if (first_name.equals(last_name)) { System.out.println("The First Name matches the Last Name."); } else { System.out.println("The First Name does not match the Last Name."); } } }
Output:
run:
The First Name does not match the Last Name.
BUILD SUCCESSFUL (total time: 0 seconds)
The output shows the string objects are not the same. This is because equals() method is case sensitive, and since the second string object we have assigned a capital C to its first characters, it sees the string objects as different.
equalsIgnoreCase() method
The string equalsIgnoreCase() method compares the same as equals() method. It compares strings if they have the same characters, the same sequence but ignores the case-sensitive check. If the two strings have the same characters and are of the same sequence it does not determine if they are of the same case or not, but the program treats them as the same. It’s case insensitive.
Example:
package stringcomparison public class StringComparison { public static void main(String[] args) { String first_name = new String ("codeunderscored"); String last_name = new String ("CODEUNDERSCORED"); if (first_name.equalsIgnoreCase(last_name)) { System.out.println("The First Name matches the Last Name."); } else { System.out.println("The First Name does not match the Last Name."); } } }
Output:
run:
The First Name matches the Last Name.
BUILD SUCCESSFUL (total time: 0 seconds)
String compare by using compareTo() and compareToIgnoreCase() methods.
String compareTo() method
It’s used for comparing two strings lexicographically. Lexicographically means the words are sorted in dictionary/alphabetical order. So we can say that two strings are lexicographically equal if they contain the same number of characters in the same position and are of the same length. You compare from left to right the two strings.
Let’s consider some scenarios to have a deep understanding of the compareTo() method outputs. You have StringC and StringD.
stringC.compareTo( stringD )
If the StringC and StringD are lexicographically equal, the program returns 0.
If StringC comes first, it returns a negative value.
If StringD comes first, it returns a positive value.
Examples:
“Ant”.compareTo ”ant” – it returns a negative integer because uppercase ‘A’ comes before lower case ‘a.’
“evening”.compareTo “everywhere” – returns a negative integer, letter ‘n’ comes before letter ‘r.’
“morning”.compareTo” morning” – returns 0, they have the same characters in the same position and also the same length.
“Morning”.compareTo ”evening” – returns a positive value since the letter ‘e’ comes after the letter ‘m.’
“Moses”.compareTo ”Njoroge” – returns a positive value since the letter ‘n’ comes after the letter ‘m.’
package stringcomparison; public class StringComparison { public static void main(String[] args) { //"Ant".compareTo "ant" – it returns a negative integer because uppercase 'A' comes before lower case 'a' String a = "ant"; String b = "Ant"; int different= a.compareTo(b); System.out.println(""Ant".compareTo "ant":\n Negative value:" +different); System.out.println("============================================================"); //"evening".compareTo "everywhere" – returns a negative integer, letter 'n' comes before letter 'r' String c = "evening"; String d = "everywhere"; int differ= c.compareTo(d); System.out.println(""evening".compareTo "everywhere:\n Negative value:" +differ); System.out.println("============================================================"); //"morning".compareTo" morning" – returns 0, they have the same characters in the same position and also the same length. String e = "morning"; String f = "morning"; int diff= e.compareTo(f); System.out.println(""morning".compareTo" morning":\n Return 0 value:" +diff); System.out.println("============================================================"); //"Morning".compareTo "evening" – returns a positive value since the letter 'e' comes after the letter 'm' String g = "morning"; String h = "evening"; int dif= g.compareTo(h); System.out.println(""Morning".compareTo "evening":\n Positive value:" +dif); System.out.println("============================================================"); //"moses".compareTo "njoroge" – returns a positive value since the letter 'm' comes after the letter 'n' String i = "moses"; String j = "njoroge"; int di= i.compareTo(j); System.out.println(""Morning".compareTo "evening":\n Positive value:" +di); } }
Output:
run:
“Ant”.compareTo ”ant”:
Negative value:32
============================================================
“evening”.compareTo “everywhere:
Negative value:-4
============================================================
“morning”.compareTo” morning”:
Return 0 value:0
============================================================
“Morning”.compareTo ”evening”:
Positive value:8
============================================================
“Morning”.compareTo ”evening”:
Positive value:-1
BUILD SUCCESSFUL (total time: 0 seconds)
compareToIgnoreCase()
The method compareTo() is also case sensitive. To remove this case sensitivity we use, compareToIgnoreCase(). It compares two strings without regard to upper case or lowercase.
Example:
package stringcomparison; public class StringComparison { public static void main(String[] args) { //"Ant".compareTo "ant" – it returns a negative integer because uppercase 'A' comes before lower case 'a' String a = "morning"; String b = "MORNING"; int different= a.compareToIgnoreCase(b); System.out.println("value:" +different); } }:
Output:
run:
value:0
BUILD SUCCESSFUL (total time: 1 second)
The above program views the two strings as the same despite their difference in cases.
Conclusion
In this tutorial, we have learned about string comparison in java. Generally, there are 3 ways to compare strings in java: equals(), compareTo(), and using the == operator. The equalsIgnoreCase() case and compareToIgnoreCase() are used when we don’t want the Upper case or Lower case considered during the comparison. I believe you can now be in a position to compare strings in java.