📜  Java equalsIgnoreCase vs equals - Java (1)

📅  最后修改于: 2023-12-03 15:01:29.741000             🧑  作者: Mango

Java equalsIgnoreCase vs equals

Introduction

In Java, equals() and equalsIgnoreCase() are two popular string comparison methods used to compare two strings. Both methods compare the contents of two strings, but there are some key differences between them. In this article, we will explore the differences between equals() and equalsIgnoreCase() and when to use each method.

equals()

The equals() method is a case-sensitive method, which means it compares two strings byte by byte, and if they are not equal, it returns false. In other words, if the character case of two strings is not the same, equals() method will return false. Here is an example:

String str1 = "Hello World";
String str2 = "hello world";
String str3 = "Hello World";
 
System.out.println(str1.equals(str2));    // This will return false
System.out.println(str1.equals(str3));    // This will return true
equalsIgnoreCase()

As the name suggests, equalsIgnoreCase() method is not case-sensitive. It compares two strings without considering their character case. It returns true if the contents of two strings are the same, regardless of their character case. Here is an example:

String str1 = "Hello World";
String str2 = "hello world";
String str3 = "Hello World";
 
System.out.println(str1.equalsIgnoreCase(str2));    // This will return true
System.out.println(str1.equalsIgnoreCase(str3));    // This will return true
When to use each method?
  1. Use equals() when you want to compare two strings and want to consider their character case.
  2. Use equalsIgnoreCase() when you want to compare two strings but don't care about their character case.
Conclusion

In conclusion, both equals() and equalsIgnoreCase() are used to compare two strings in Java, but they are not the same. equals() is case-sensitive, while equalsIgnoreCase() is not. Before using one of these methods to compare two strings, make sure to identify the requirements of your program and use the corresponding method accordingly.