Compare Two Strings in Java Without Using equals() — Definition, Examples and Program

Learn how to compare two strings in Java without using the equals() method. This blog explains character-by-character comparison with examples, a Java program, and practice challenges.

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:

How the Logic Works

  1. If the lengths of both strings are different, they are not equal.
  2. If lengths are same, compare characters at each index.
  3. If any character mismatches, strings are not equal.
  4. If all characters match, strings are equal.

Example 1

String 1: "Java"

String 2: "Java"

Comparison:

Result: Strings are Equal

Example 2

String 1: "Hello"

String 2: "Hella"

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

Practice Challenges

  1. Modify the program to perform case-insensitive comparison.
  2. Compare strings without using length().
  3. Count how many characters differ between two strings.

Manual string comparison builds a strong foundation for solving advanced string problems in Java.