Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

If you have a few years of Linux experience, and you're interested in sharing that with the community (and getting paid for your work of course), have a look at the "Write for Us" page. Cheers. Eugen

1. Overview

In this tutorial, we’ll cover the toUpperCase and toLowerCase methods included in the Java String class.

We’ll start by creating a String called name:

String name = "John Doe";

2. Convert to Uppercase

To create a new uppercase String based on name, we call the toUpperCase method:

String uppercaseName = name.toUpperCase();

This results in uppercaseName having the value “JOHN DOE”:

assertEquals("JOHN DOE", uppercaseName);

Note that Strings are immutable in Java and that calling toUpperCase creates a new String. In other words, name is unchanged when calling toUpperCase.

3. Convert to Lowercase

Similarly, we create a new lowercase String based on name by calling toLowerCase:

String lowercaseName = name.toLowerCase();

This results in lowercaseName having the value “john doe”:

assertEquals("john doe", lowercaseName);

Just as with toUpperCasetoLowerCase does not change the value of name.

4. Change Case Using Locales

Additionally, by supplying a Locale to the toUpperCase and toLowerCase methods, we can change the case of a String using locale-specific rules.

For example, we can supply a Locale to uppercase a Turkish i (Unicode 0069):

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

Accordingly, this results in an uppercase I and a dotted uppercase I:

I
İ

We can verify this using the following assertions:

assertEquals("\u0049", "\u0069".toUpperCase());
assertEquals("\u0130", "\u0069".toUpperCase(TURKISH));

Likewise, we can do the same for toLowerCase using the Turkish I (Unicode 0049):

System.out.println("\u0049".toLowerCase());
System.out.println("\u0049".toLowerCase(TURKISH));

Consequently, this results in a lowercase i and a lowercase dotless i:

i
ı

We can verify this using the following assertions:

assertEquals("\u0069", "\u0049".toLowerCase());
assertEquals("\u0131", "\u0049".toLowerCase(TURKISH));

5. Conclusion

In conclusion, the Java String class includes the toUpperCase and toLowerCase methods for changing the case of a String. If needed, a Locale can be supplied to provide locale-specific rules when changing the case of a String.

The source code for this article, including examples, can be found over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

Leave a Reply

avatar
  Subscribe  
Notify of