22 Votes

Java: Case Insensitive Equals - String Comparison

Info by Anja Proggy | Last update on 2024-07-22 | Created on 2013-12-08

Some time ago, when comparing two Strings in Java and the comparison should be executed case insensitive independent from the uppercase or lowercase writing of the String, I have turned the whole String in upper or lower case letters before the comparison:

String s1 = "test";
String s2 = "Test";

if (s1.toUpperCase().equals(s2.toUpperCase())) {
  
}

In this example, both "test" as well as "Test" become "TEST" and the result of the comparison will be true.

But not long ago, I experienced that it can be so simple:

String s1 = "test";
String s2 = "Test";

if (s1.equalsIgnoreCase(s2)) {

}

With the function .equalsIgnoreCase() Java is providing a method fitting perfect for this scenario making your code simple and easier to read. Especially when performing long comparisons, this is a good practice to use.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.