Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)

The String class provides methods to change a string to uppercase or lowercase. That is, you can change all characters in a string to uppercase, or all characters to lowercase.

toUpperCase()

toUpperCase() changes the string to all uppercase. upper case means upper case.

String str = "Hello World";
System.out.println(str.toUpperCase());

str = "hello world";
System.out.println(str.toUpperCase());

Output:

HELLO WORLD
HELLO WORLD

toLowerCase()

toLowerCase() changes the string to all uppercase. lower case means lower case.

String str = "Hello World";
System.out.println(str.toLowerCase());

str = "HELLO WORLD";
System.out.println(str.toLowerCase());

Output:

hello world
hello world

Change the case of different languages

In the example above, toUpperCase() changed the English string to all uppercase letters. In fact, this method does not change for English, but for the language returned by Locale.getDefault().

By default Locale.getDefault().getLanguage() returns english, so it seemed to convert to uppercase for english.

// String.java
public String toLowerCase() {
    return toLowerCase(Locale.getDefault());
}

However, if you pass Locale as an argument as follows, you can implement to change strings in other languages to all uppercase letters.

// String.java
public String toUpperCase(Locale locale)

Taking Turkish as an example, you can change it to uppercase like this:

Locale TURKISH = new Locale("tr");
System.out.println("\u0069".toUpperCase());
System.out.println("\u0069".toUpperCase(TURKISH));

Output:

I
İ

In the case of toLowerCase(), you can pass Locale as an argument in the same way. Apply as above.

public String toLowerCase(Locale locale)

Compare case-insensitively

equals() performs case-sensitive comparisons. On the other hand, equalsIgnoreCase() does a case-insensitive string comparison.

String str = "Hello";
System.out.println("equals ? " + "hello".equals(str));
System.out.println("equalsIgnoreCase ? " + "hello".equalsIgnoreCase(str));

Output:

equals ? false
equalsIgnoreCase ? true

So, to make a case-insensitive comparison, you can use equalsIgnoreCase().

codechachaCopyright ©2019 codechacha