Sunday, November 24, 2024

How to Compare Strings in Java Without Case Sensitivity: A Complete Guide with Examples

 How to Compare Strings in Java Without Case Sensitivity: A Complete Guide with Examples


To compare two strings without considering case sensitivity in Java, you can use the following approaches:

1. Using equalsIgnoreCase()

The String class in Java provides the method equalsIgnoreCase() to compare two strings without considering case.

Example:


public class StringComparisonExample { public static void main(String[] args) { String str1 = "Hello"; String str2 = "hello"; if (str1.equalsIgnoreCase(str2)) { System.out.println("The strings are equal (case-insensitive)."); } else { System.out.println("The strings are not equal."); } } }

Output:

The strings are equal (case-insensitive).

2. Using toLowerCase() or toUpperCase()

You can convert both strings to the same case (e.g., lower or upper) before comparing them using equals().

Example:

public class StringComparisonExample { public static void main(String[] args) { String str1 = "Hello"; String str2 = "hello"; if (str1.toLowerCase().equals(str2.toLowerCase())) { System.out.println("The strings are equal (case-insensitive)."); } else { System.out.println("The strings are not equal."); } } }

Output:

The strings are equal (case-insensitive).

3. Using compareToIgnoreCase()

The compareToIgnoreCase() method compares two strings lexicographically, ignoring case differences.

Example:

public class StringComparisonExample { public static void main(String[] args) { String str1 = "Hello"; String str2 = "hello"; if (str1.compareToIgnoreCase(str2) == 0) { System.out.println("The strings are equal (case-insensitive)."); } else { System.out.println("The strings are not equal."); } } }

Output:

The strings are equal (case-insensitive).

Key Points:

  • Use equalsIgnoreCase() for a straightforward case-insensitive comparison.
  • toLowerCase() or toUpperCase() allows you to manipulate and compare strings more flexibly.
  • compareToIgnoreCase() is useful for sorting or lexicographical comparison.

No comments:

Post a Comment

Understanding Essential DNS Record Types for Web Administrators

  Understanding Essential DNS Record Types for Web Administrators Introduction The Domain Name System (DNS) acts as the backbone of the inte...