For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Have you ever wondered how you register for different websites and it has two sections for your password? One says “New Password'' and the other one says “Confirm Password”. Have you ever faced a prompt saying “Passwords do not match”? That is what String comparison is all about. Let’s delve into this blog and see what String comparison in Java is all about.
String comparison in Java is basically comparing two Strings to check whether they match or not. As Strings are objects, it require methods or operators to check whether they are identical or not.
We will delve into comparing Strings in Java by using different methods such as equals(), equalsIgnoreCase(), compareTo(), compareToIgnoreCase(), and the == operator. We shall also type in a code that will compare two strings manually using the for loop and conditional statements. Keep reading to find out more about string comparison in Java.
There are multiple ways through which you can compare Strings in Java. Let’s get into the inbuilt methods that Java provides users to compare Strings in the section below:
Code:
public class upGradTutorials{
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "hello";
boolean areEqual = str1.equals(str2);
System.out.println(areEqual);
}
}
Output:
false
In the example above, we are taking two Strings, str1 containing Hello and str2 containing Hello and hello. Note that these two Strings aren’t the same in their casing. We then declare a boolean variable areEqual, and then compare both strings using the equals() function.
This boolean variable will return either a true value if both the Strings are exactly identical or false if they are not. We then print the value of the boolean variable areEqual and it returns a false value as str1 and str2 are not identical.
In the above string comparison in Java program, we saw that the strings were the same but had different casing. The equalsIgnoreCase method compares two strings and ignores if there’s a difference in the casing.
Below is the code for comparing two Strings in Java using the equalsIgnoreCase() method:
Code:
public class upGradTutorials{
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "hello";
boolean areEqual = str1.equalsIgnoreCase(str2);
System.out.println(areEqual);
}
}
Output:
true
In the code above, we do the same that we did while using the equals() method. But we use the equalsIgnoreCase() so the output is true as it is the same String, but the casing is different. The code compares two strings, str1, and str2.
This method checks if the strings are equal, ignoring the case of the characters. In this case, str1 is assigned the value "Hello", and str2 is assigned the value "hello". Despite the difference in the case, the equalsIgnoreCase() method considers them equal and returns true. The result is stored in the areEqual variable. Finally, the value of areEqual is printed using System.out.println(), which will output true.
The compareTo method can also be used to compare Strings in Java. The only difference between equals() and compareTo() methods is that the equals() method returns a boolean value, i.e., true or false, while the compareTo() method returns an integer value, i.e., positive/ negative, or 0 and it compares the strings lexicographically.
Below is the code for comparing two strings in Java using the compareTo() method:
Code:
public class upGradTutorials{
public static void main(String[] args) {
String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);
System.out.println(result);
}
}
Output:
-1
In the code above, we take two Strings str1 and str2. We set str1 as apple and str2 as banana. We declare an integer call result. We then use the compareTo() function to compare str1 to str2 and then print the result using System.out.println(). This returns the value of -1 as the strings do not match.
Do it yourself: Try declaring the value of str2 as apple and see what the result is.
This method is just like the equalsIgnoreCase method. So we take two strings str1, str2, containing Apple and apple as values and run them through the compareToIgnoreCase() method. We will get a result of 0 as the method does not take casing into consideration and determines that both the strings are the same, i.e., returns a true value.
Code:
public class upGradTutorials{
public static void main(String[] args) {
String str1 = "Apple";
String str2 = "apple";
int result = str1.compareToIgnoreCase(str2);
System.out.println(result);
}
}
Output:
0
First, two string variables are declared: str1 and str2. str1 is assigned the value "Apple," and str2 is assigned the value "apple". The compareToIgnoreCase() method then performs a lexicographic comparison of the strings, considering the Unicode values of the characters, but without distinguishing between uppercase and lowercase letters. It returns an integer value that represents the comparison result.
If the result is less than 0, it means str1 comes before str2 in lexicographical order. If the result is greater than 0, it means str1 comes after str2. If the result is 0, it means both strings are equal. The result of the comparison is stored in the result variable. Finally, the System.out.println() statement is used to print the value of result.
There is another way to perform string comparison in Java, and that is by using the == operator. The == operator Checks whether two strings are in the same memory location or not. This operator is not used to check the content equality but to see whether they refer to the same location in memory.
Below is the code to compare two strings using the == operator:
Code:
public class upGradTutorials{
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
boolean areEqual = (str1 == str2);
System.out.println(areEqual);
}
}
Output:
true
In the code above, we take two strings str1 and str2, having the same value, Hello. We then use the == operator to check whether both the strings point to the same location in memory or not. Since they do, we get an output of true as areEqual is a boolean variable.
Code:
public class upGradTutorials{
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
boolean areEqual = customCompare(str1, str2);
System.out.println(areEqual);
}
public static boolean customCompare(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
for (int i = 0; i < str1.length(); i++) {
char ch1 = str1.charAt(i);
char ch2 = str2.charAt(i);
if (ch1 != ch2) {
return false;
}
}
return true;
}
}
Output:
true
In the example above, we have a function that performs the same as the equals() method in Java. We set str1 and str2 to the same value Hello, and pass it through a function customCompare. This function customCompare returns a boolean value that we store into the variable areEqual and then print the result.
The customCompare function takes two strings as parameters and checks whether both strings have the same length. It returns a false value if the strings do not have the same length. If they are of the same length, a for loop is used to loop through the string’s length - 1 as the index of a string starts from 0 and ends length-1 of the string.
A charAt() function is then used to take each character out of both the strings and then compare each character one by one. If one character does not match, then the customCompare() function returns a false value. Otherwise, it returns a true value.
This is how the equals() function works at the most basic level and can be tweaked for string comparison in whatever way the coder deems fit.
String comparison has a lot of real-world applications starting from user authentication, the ‘Find and replace’ function, spell checkers, and lookups in dictionaries.
String comparison also makes its way into more complex applications such as the Boyer-Moore or Knuth-Morris-Pratt algorithms, DNA sequencing, version control systems, and more.
1. How can I compare two Strings in Java having leading or trailing whitespaces?
You can use the trim() function to delete any leading or trailing whitespaces in the String and then use the equals() or compareTo() function to compare the two Strings.
2. Can I perform a numeric comparison of Strings in Java?
If you take a number as input in a string variable then you have to use the Integer.parseInt() function and then pass the String variable in it as a parameter. Once you do that, the number gets converted into an Integer data-type from a String- data type and you can use ‘>, <, ==, >=, <=’ to compare them.
3. What do you mean by lexicographically comparing two strings?
Lexicographic comparison is basically comparing two strings according to the alphabetical sequence of their characters. So each character in a string is compared sequentially from left to right in alphabetical order.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.