Learn different ways to compare strings in Java using equals()
, equalsIgnoreCase()
, ==
, and compareTo()
methods. This guide includes step-by-step examples, logic breakdowns, and custom comparison techniques for better understanding.
Required Knowledge
- Java programming basics
- Java operators
- String class methods
Problem Statement
Write a Java program to compare two strings and determine if they are equal. The program should accept two string inputs and check for equality, considering different comparison methods such as case sensitivity. Depending on the chosen method, the program should return a result indicating whether the strings are identical or not.
For example:
Input: “Hi” and “hi”
Output: true
(if using equalsIgnoreCase()
method)
Output: false
(if using equals()
method)
Explanation:
Input String str1: "Hi"
Input String str2: "hi"
str1 and str2 both has same text with different test cases (Uppercase and Lowercase).
By updating str2 with uppercase letters, it will become "HI".
Now str1 = str2
As both strings are equal then we say "true".
Logic to Compare two Strings
There are multiple logics to compare two strings in java programming language.
Logic 1: Using equals() and equalsIgnoreCase() method
- In order to achieve comparison of two strings using equals() and equalsIgnoreCase() methods, we need to initialize two strings str1 and str2 with some text by asking the user.
- Compare str1 and str2 using the equalsIgnoreCase method.
- This method returns true if the two strings are equal, ignoring case differences. And print the result
- Compare str1 and str2 using the equals method.
- This method returns true if the two strings are exactly equal, considering case differences. And print the result.
Logic 2: Using == operator
- To to do string comparison of two strings using == operator, we need to initialize two strings str1 and str2 with some text.
- A third variable (str3) is created using the new keyword with some text in it.
- Compare str1 and str2 using == operator. If both variables hold the same text, they reference the same object in memory (string pool). it will return true
- Compare str1 and str3 using == operator. Even if str1 and str3 have the same data, str3 is created as a new object in memory using the new keyword. As a result, str1 and str3 reference different objects in memory, so this comparison returns false. And print the result.
Logic 3: Using compareTo() method and compareToIgnoreCase() method
- In order to achieve comparison of two strings using compareTo() and compareToIgnoreCase() method, first we need to initialize two strings str1 and str2 with some text by asking the user.
- Use the compareTo method to compare str1 and str2. This method returns 0 if the strings are lexicographically (order of characters based on their unicodes) equal and store the result of the comparison in a boolean variable equal.
- And print the equal to display the result.
- Use the compareToIgnoreCase method to compare str1 and str2. This method also returns 0 if the strings are lexicographically equal, ignoring case differences and store the result of the comparison in a boolean variable equals. Print this equals to display the result.
Logic 4: Custom method
- In order to achieve comparison of two strings by creating custom method, first we need to initialize two strings str1 and str2 with some text by asking the user.
- Create a method which takes strings (s1 and s2) as input. Inside the method, check using if statement, if strings are null or not, if any one of the strings are null, we will return false.
- If they are not null then, we will compare length of the strings, if their lengths are not equal, it will return false and if lengths are equal using another if statement.
- Use for loop to iterate through any one strings as their lengths are equal.
- Inside the for loop, compare each character using if statement. And call this method in the main and print the result.
Java program to compare two Strings
ā Ā Program 1: Using equals() and equalsIgnoreCase() method
In the below program we are using equals() and equalsIgnoreCase() method to compare two strings.
import java.util.Scanner;
public class StringComparison{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Please enter a text");
String str1 = s.nextLine();
System.out.println("Please enter second text");
String str2 = s.nextLine();
System.out.println("Result with case ignorance: "+str1.equalsIgnoreCase(str2));
System.out.println("Result without case ignorance/with equals method: "+ str1.equals(str2));
s.close();
}
}
Output:
Please enter a text
Hi
Please enter second text
hi
Result with case ignorance: true
Result without case ignorance/with equals method: false
š§ Ā Explanation:
- A
Scanner
object is created to read input from the user. - The program asks the user to enter the first string, which is stored in
str1
. - The program asks the user to enter the second string, which is stored in
str2
. - The program compares
str1
andstr2
usingequalsIgnoreCase
, which ignores case differences, and prints the result. - The program compares
str1
andstr2
usingequals
, which considers case differences, and prints the result. - The
Scanner
object is closed to release system resources.
ā Program 2: Using == operator
In the below program we are using == (double =)operator to compare two strings.
public class StringComparison {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
System.out.println("Result is: " + (str1 == str2));
System.out.println("Result is: " + (str1 == str3));
}
}
Output:
Result is: true
Result is: false
š§ Ā Explanation:
- The program defines a class
StringComparison
with amain
method. str1
andstr2
are both assigned the string literal “Hello”.str3
is created using thenew
keyword, which creates a new string object with the same value “Hello”.- The program compares
str1
andstr2
using the==
operator; since both refer to the same object in the string pool, the result istrue
. - The program compares
str1
andstr3
using the==
operator; sincestr3
is a new object, the result isfalse
. - The results of these comparisons are printed to the console.
ā Program 3: Using compareTo() and compareToIgnoreCase() method
In the below program we are using compareTo() method and compareToIgnoreCase() method to compare two strings.
import java.util.Scanner;
public class CompareStrings2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the first text");
String str1 = s.nextLine();
System.out.println("Enter the second text");
String str2 = s.nextLine();
boolean equal = str1.compareTo(str2) == 0;
System.out.println("Two strings are equal or not (comapreTo): " + equal);
boolean equals = str1.compareToIgnoreCase(str2) == 0;
System.out.println("Two strings are equal or not (comapreToIgnoreCase): " + equals);
s.close();
}
}
Output:
Enter the first text
Interview Expert
Enter the second text
inTerView eXpert
Two strings are equal or not (comapreTo): false
Two strings are equal or not (comapreToIgnoreCase): true
š§ Ā Explanation:
- The program defines a class named
CompareStrings2
with amain
method as the entry point. - A
Scanner
object is created to read input from the user. - The program asks the user to enter the first string, which is stored in
str1
. - The program asks the user to enter the second string, which is stored in
str2
. - The program compares
str1
andstr2
using thecompareTo
method. This method returns0
if the strings are lexicographically equal. The result is stored in a boolean variableequal
and printed to the console. - The program compares
str1
andstr2
using thecompareToIgnoreCase
method. This method also returns0
if the strings are lexicographically equal, ignoring case differences. The result is stored in a boolean variableequals
and printed to the console. - The
Scanner
object is closed to release resources.
ā Program 4: Custom method
In the below program we are creating a custom method to compare two strings.
import java.util.Scanner;
public class CompareStrings {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter first text");
String str = s.nextLine();
System.out.println("Enter second text");
String str1 = s.nextLine();
boolean result = compareStrings(str, str2);
System.out.println("Two strings are equal??: " + result);
s.close();
}
public static boolean compareStrings(String s1, String s2) {
if (s1 == null || s2 == null)
return false;
if (s1.length() != s2.length())
return false;
for (int i = 0; i < s1.length(); i++) {
if (s1.charAt(i) != s2.charAt(i))
return false;
}
return true;
}
}
Output:
Enter first text
Hi
Enter second text
Hi
Two strings are equal??: true
š§ Ā Explanation:
- The program uses Scanner to input two strings from the user.
- It defines a main method as the entry point of the program.
- In the main method:
- It asks for and stores the user’s input for two strings.
- It calls the compareStrings method with the input strings and stores the result.
- It prints whether the two strings are equal or not.
- Finally, it closes the Scanner object.
- Outside the main method, there’s a compareStrings method:
- It checks for null strings and returns false if either is null.
- It checks if the lengths of the strings are different and returns false if so.
- It iterates through each character of the strings, comparing them.
- If any characters are different, it returns false.
- If all characters are the same, it returns true, indicating equality.
Conclusion
The java programs we did here compares two strings using equals(), equalsIgnoreCase(), compareTo() and by creating a custom method.