Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
Now Reading
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
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.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...