Compare Two Strings in Java Without Using equals()
In Java, strings are commonly compared using the equals() method.
However, understanding how to compare strings manually helps you learn how strings actually work internally.
In this approach, we compare two strings:
- By checking their lengths
- By comparing each character one by one
How the Logic Works
- If the lengths of both strings are different, they are not equal.
- If lengths are same, compare characters at each index.
- If any character mismatches, strings are not equal.
- If all characters match, strings are equal.
Example 1
String 1: "Java"
String 2: "Java"
Comparison:
- J == J ✔
- a == a ✔
- v == v ✔
- a == a ✔
Result: Strings are Equal
Example 2
String 1: "Hello"
String 2: "Hella"
- H == H ✔
- e == e ✔
- l == l ✔
- l == l ✔
- o ≠ a ✖
Result: Strings are Not Equal
Java Program to Compare Two Strings Without equals()
import java.util.Scanner;
public class CompareStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = sc.nextLine();
System.out.print("Enter second string: ");
String str2 = sc.nextLine();
boolean isEqual = true;
if (str1.length() != str2.length()) {
isEqual = false;
} else {
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) != str2.charAt(i)) {
isEqual = false;
break;
}
}
}
if (isEqual) {
System.out.println("Strings are Equal");
} else {
System.out.println("Strings are Not Equal");
}
}
}
Sample Output
Enter first string: programming
Enter second string: programming
Strings are Equal
Enter first string: Java
Enter second string: java
Strings are Not Equal
Important Notes
- This comparison is case-sensitive.
- Characters are compared using ASCII values.
- This method mimics the internal behavior of
equals().
Practice Challenges
- Modify the program to perform case-insensitive comparison.
- Compare strings without using
length(). - Count how many characters differ between two strings.
Manual string comparison builds a strong foundation for solving advanced string problems in Java.