Skip to content

Commit d6b4695

Browse files
authored
Add blogpost 'How to compare Strings in Java'
I have added images folder and blogpost 'How to compare Strings in Java'
1 parent 6ebe6be commit d6b4695

File tree

1 file changed

+290
-0
lines changed

1 file changed

+290
-0
lines changed
Lines changed: 290 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,290 @@
1+
```
2+
layout: post
3+
title: How Do I Compare Strings In Java
4+
author: gaurav
5+
categories: Java, Core Java, String
6+
image:
7+
description: In this article you are going to learn how to compare strings. What problem occurs when you compare string using `equals to` (`=`)operator.
8+
featured: true
9+
```
10+
11+
In this article you are going to learn how to compare strings. What problem occurs when you compare string using `equals to` (`=`)operator.
12+
13+
## Introduction
14+
15+
The `String` is a special Class in Java. We use String regularly in Java programs, so comparing two string is a common practice in Java. In this article I tried to answer the most common questions about the string, ‘How do I compare strings in Java?’
16+
17+
Comparing strings is very helpful the processes like authentication, sorting, reference matching, etc.
18+
19+
I have listed 3 ways to compare strings in Java.
20+
21+
1. Using `equals()` method ( comparing the content)
22+
23+
2. Using `==` operator (comparing the object reference)
24+
25+
3. Using `compareTo()` method (comparing strings lexicographically)
26+
27+
## 1. Compare strings using `equals()` method
28+
29+
In this way, I am using `.equals()` instance method of the String class. Originally `.equals()` method is the `Object` class method, String class overrides it.
30+
31+
`**equals()**` **method the compare two strings for value equality, weather they are logically equal.**
32+
33+
`equals()` method in String class takes another string a parameter and compare it with the specified string, it returns `true` if and only if the parameter string is not null and contains the same characters as the specified string.
34+
35+
```
36+
public boolean equals(Object anObject)
37+
38+
It compare this string with the argument strings and return true if the argument is not null and contains the same character as the specified string.
39+
40+
param -
41+
another string
42+
43+
returns -
44+
45+
true - if argument is not null and it contains same characters as the specified string
46+
false - if the argument is null or it does not contain same characters as the specified string
47+
48+
ex. firstString.equals(secondString)
49+
// returns true if and only if the secondString is not null and contains the same characters as firstString.
50+
```
51+
52+
I have given the program to compare string using `equals()` method below
53+
```
54+
/**
55+
* A Java program to compare two strings using equsls()
56+
* and equalsIgnoreCase() method of the String.
57+
*
58+
* @author Gaurav Kukade at coderolls.com
59+
*/
60+
61+
public class CompareUsingEquals {
62+
63+
public static void main(String[] args) {
64+
String firstString = "coderolls";
65+
String secondString = "javablog";
66+
String thirdString = "coderolls";
67+
String fourthString = "CodeRolls";
68+
69+
System.out.println("Comparing strings using equals() and equalsIgnoreCase() method\n");
70+
71+
// Using equals() method
72+
System.out.print("firstString.equals(secondString) : ");
73+
System.out.println(firstString.equals(secondString));
74+
75+
System.out.print("firstString.equals(thirdString) : ");
76+
System.out.println(firstString.equals(thirdString));
77+
78+
/*
79+
* Using equalsIgnoreCase() method to ignore
80+
* case consideration (i.e. Capital or small) of both the strings.
81+
*/
82+
System.out.print("firstString.equalsIgnoreCase(fourthString) : ");
83+
System.out.println(firstString.equalsIgnoreCase(fourthString));
84+
}
85+
86+
}
87+
```
88+
89+
Output:
90+
91+
```
92+
Comparing strings using equals() and equalsIgnoreCase() method
93+
94+
firstString.equals(secondString) : false
95+
firstString.equals(thirdString) : true
96+
firstString.equalsIgnoreCase(fourthString) : true
97+
```
98+
99+
## 2. Compare strings using `==` operator
100+
101+
**In String,** `**==**` **operator is used to comparing the reference of the given strings, whether they are referring to the same objects.**
102+
103+
When you compare two strings using `==` operator, it will return `true` if the string variables are pointing toward the same java object, else it will return `false`.
104+
105+
I have given a Java program to compare using `==` operator below
106+
```
107+
/**
108+
* A Java program to compare strings using == operator.
109+
*
110+
* == operator ckecks weather both the strings referring
111+
* to the same String Object.
112+
*
113+
* @author Gaurav Kukade at coderolls.com
114+
*/
115+
116+
public class CompareUsingEqualsToOperator {
117+
118+
public static void main(String[] args) {
119+
120+
String firstString = "coderolls";
121+
String secondString = "javablog";
122+
String thirdString = "coderolls";
123+
124+
// creating new String object with the same value as firstString or thirdString
125+
String fourthString = new String("coderolls");
126+
127+
System.out.println("Comparing strings using == operator \n");
128+
129+
System.out.print("firstString == secondString : ");
130+
System.out.println(firstString == secondString);
131+
132+
/*
133+
* Here firstString and thirdString is referring to the same String object
134+
* hence it will print 'true'.
135+
*/
136+
System.out.print("firstString == thirdString : ");
137+
System.out.println(firstString == thirdString);
138+
139+
/*
140+
* Here firstString and fourthString have same value
141+
* but they are referring to the different String object.
142+
*
143+
* hence it will print 'false'
144+
*/
145+
System.out.print("firstString == fourthString : ");
146+
System.out.println(firstString == fourthString);
147+
}
148+
149+
}
150+
```
151+
152+
Output:
153+
154+
```
155+
Comparing strings using == operator
156+
157+
firstString == secondString : false
158+
firstString == thirdString : true
159+
firstString == fourthString : false
160+
```
161+
162+
## Problem with using `==` operator for string comparison
163+
164+
Most of the beginner Java developers commit this mistake by comparing two strings using the == operator.
165+
166+
Logically, they have to check whether both the string contains the same character sequence or not.
167+
168+
In Java String, the `==` operator used to check the reference of both the string objects and `equals()` method used to check the value equality of both strings.
169+
170+
`==` – checks reference equality
171+
172+
`equals()` – checks the value equality
173+
174+
When we assign a string value to the string variable JVM will check if the string with the equal value already present in the string pool or not. If it is not present in the string pool, it will be added to the constant pool and the reference to that string object is returned.
175+
176+
If it is present in the string pool, the reference to the memory address of that string object is returned.
177+
178+
The following image shows the pictorial explanation of the same.
179+
180+
!['firstString' pointing towards the "coderolls" string in string pool](/assets/images/2019-12-10/firstString-pointing-to-coderolls-in-string-pool.png)
181+
182+
‘firstString’ pointing towards the “coderolls” string in string pool
183+
184+
If we are assigning the equal value to another string variable, JVM checks if the string with that value is present in the string constant pool or not.
185+
186+
Since the string object with that value is already created in the previous step. Another string variable starts referring to the previously created string object instance.
187+
188+
The following image shows the pictorial explanation for the same
189+
190+
!['firstString' and 'secondString' pointing towards the "coderolls" string in string pool](/assets/images/2019-12-10/secondString-pointing-to-coderolls-in-string-pool.png)
191+
192+
‘firstString’ and ‘secondString’ pointing towards the “coderolls” string in string pool
193+
194+
When we create string using the `new` operator, a new string object is created and stored in the Java heap space.
195+
196+
!['firstString' and 'secondString' pointing towards the "coderolls" string in string pool and 'thirdString' pointing towards the "coderolls" in java heap space.](/assets/images/2019-12-10/thirdString-pointing-to-coderolls-in-heap.png)
197+
198+
‘firstString’ and ‘secondString’ pointing towards the “coderolls” string in string pool and ‘thirdString’ pointing towards the “coderolls” in java heap space.t
199+
200+
## 3. Compare strings using `compareTo()` method
201+
202+
`compareTo()` method is used to compare two strings lexicographically. i.e. Alphabetically.
203+
204+
`compareTo()` method compares the character sequence of the argument string with the character sequence of the specified string.
205+
206+
![Showing argument string and specified string.](https://coderolls.com/wp-content/uploads/2019/08/showing-argument-string-and-specified-string.png)
207+
208+
Showing argument string and a specified string.
209+
210+
It returns a negative integer if the argument string is lexicographically greater than the specified string. i.e if the argument string follows the specified string. ( argument String > specified String )
211+
212+
It returns positive integer if the argument string is lexicographically smaller than the specified string. i.e. If the argument string precedes the specified string. ( argument String < specified String )
213+
214+
It returns zero if both the strings are lexicographical equals. ( argument String = specified String )
215+
216+
If you want to ignore the cases of both the string use `compareToIgnoreCase()` method.
217+
218+
I have given a program for comparing strings using the `compareTo()` method. It also consists a case for ignoring the cases with `compareToIgnoreCase()` method.
219+
```/**
220+
* A Java program to compare strings using compareTo()
221+
* and compareToIgnoreCase() method.
222+
*
223+
* compareTo() compare strings lexicograpgically.
224+
*
225+
* @author Gaurav Kukade at coderolls.com
226+
*/
227+
228+
public class CompareUsingCompareTo {
229+
230+
public static void main(String[] args) {
231+
232+
String firstString = "java";
233+
String secondString = "coderolls";
234+
String thirdString = "sql";
235+
String fourthString = "CodeRolls";
236+
237+
System.out.println("Comparing strings using compareTo() and compareToIgnoreCase() method\n");
238+
239+
// Using compareTo() method
240+
System.out.print("firstString.compareTo(secondString) : ");
241+
System.out.println(firstString.compareTo(secondString));
242+
243+
System.out.print("firstString.compareTo(thirdString) : ");
244+
System.out.println(firstString.compareTo(thirdString));
245+
246+
/*
247+
* Using compareToIgnoreCase() method to ignore
248+
* case consideration (i.e. Capital or small) of both the strings.
249+
*/
250+
System.out.print("secondString.compareToIgnoreCase(fourthString) : ");
251+
System.out.println(secondString.compareToIgnoreCase(fourthString));
252+
}
253+
254+
}
255+
```
256+
View [CompareUsingCompareTo.java as GitHub Gist](https://gist.github.com/gauravkukade/dc40c37e55c6fbad08755e2281dc2ebe).
257+
258+
Output:
259+
260+
```
261+
Comparing strings using compareTo() and compareToIgnoreCase() method
262+
263+
firstString.compareTo(secondString) : 7
264+
firstString.compareTo(thirdString) : -9
265+
secondString.compareToIgnoreCase(fourthString) : 0
266+
```
267+
268+
I have written a detailed article on [how to compare strings lexicographically in java](https://coderolls.com/compare-two-strings-lexicographically-in-java/). In this article, I have also created a user-defined method to [compare two strings lexicographically](https://coderolls.com/compare-two-strings-lexicographically-in-java/), please have a look.
269+
270+
## Conclusion
271+
272+
We can compare strings using the ways given below
273+
274+
1. Using `equals()` method : `equals()` method in the strings used to check the string value equality whether they contain the same character sequence.
275+
276+
2. Using `==` operator : `==` operator used to check the reference equality of the two strings, whether they are pointing towards the same string object.
277+
278+
3. Using `compareTo()` method : `compareTo()` method used to check the strings lexicographically. I.e alphabetically. Check the detailed articles on [How to compare strings lexicographically](https://coderolls.com/compare-two-strings-lexicographically-in-java/).
279+
280+
Most of the beginner java developers do mistakes while comparing strings. They actually want to check the content of the string but they use `==` operator to check it.
281+
282+
It is always advised to use equals() method to compare the string on the basis of its content.
283+
284+
If you have any query about the code blocks given above, please write it down in the comment section below. Also. let me know if you have any other way to compare two strings in java in the comment section.
285+
286+
### Related Article
287+
288+
- [How To Reverse A String In Java (5 ways)](https://coderolls.com/reverse-a-string-in-java/)
289+
- [How To Compare Two Strings Lexicographically In Java](https://coderolls.com/compare-two-strings-lexicographically-in-java/)
290+
- [Introduction to Java Technology (Language and Platform)](https://coderolls.com/java-introduction/)

0 commit comments

Comments
 (0)