How do I make my string comparison case insensitive?

user268018 picture user268018 · Feb 8, 2010 · Viewed 283.3k times · Source

I created a Java program to compare two strings:

String s1 = "Hello";
String s2 = "hello";

if (s1.equals(s2)) {
    System.out.println("hai");
} else {
    System.out.println("welcome");
}

It displays "welcome". I understand it is case sensitive. But my problem is that I want to compare two strings without case sensitivity. I.e. I expect the output to be hai.

Answer

Michael Bavin picture Michael Bavin · Feb 8, 2010
  • The best would be using s1.equalsIgnoreCase(s2): (see javadoc)
  • You can also convert them both to upper/lower case and use s1.equals(s2)