Skip to content

← Back to Overview

Java Program - Case Insensitive Comparison

Concept Explanation

What is it?

This program checks if two strings contain the same sequence of characters, regardless of whether they are uppercase or lowercase. For example, "Java" and "java" should match.

Why is it important?

User input is often unpredictable. When checking usernames, passwords (sometimes), or search terms, case-insensitivity ensures a smoother user experience.


Algorithm

  1. Start
  2. Input two strings: str1 and str2.
  3. Use the equalsIgnoreCase() method.
  4. If true, print "Strings match".
  5. Else, print "Strings do not match".
  6. End

Implementations

import java.util.Scanner;

public class StringCompare {
    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();

        // Standard Comparison (Case Sensitive)
        System.out.println("Using equals(): " + str1.equals(str2));

        // Case Insensitive Comparison
        if (str1.equalsIgnoreCase(str2)) {
            System.out.println("Result: Strings MATCH (Ignoring Case)");
        } else {
            System.out.println("Result: Strings DO NOT MATCH");
        }

        sc.close();
    }
}

Explanation

  • Java
  • equals(): Checks for exact match (e.g., "A" != "a").
  • equalsIgnoreCase(): The standard method for this task. It internally converts both characters to uppercase/lowercase for comparison.
  • == Operator: Never use == for comparing string content! It checks memory references, not values.

Complexity Analysis

  • Time Complexity: O(n) where n is the length of the string.
  • Space Complexity: O(1)

Interview Tips

  • Explain why == returns false for new String("A") == new String("A").

"In the world of logic, similarity is as powerful as identity." - Anonymous