This post will discuss how to convert a string to uppercase and lowercase in Java.

1. Using toLowerCase()/toUpperCase() method

The standard solution to convert all of the characters in a string to lower case is calling the toLowerCase() method. Since Strings are immutable in Java, this method will create a new instance of the string.

Download  Run Code

 
It has an overloaded version that accepts a Locale. Its usage is demonstrated below. The code converts the String to lower case using the rules of the specified locale.

Download  Run Code

 
To convert a string to uppercase, the String class provides a similar method toUpperCase():

Download  Run Code

 
Note: It is advisable to place a null-check before calling the toLowerCase() or toUpperCase() method to avoid NullPointerException.

2. Using WordUtils class

Another solution is to use the WordUtils class from Apache Commons Text. It provides the uncapitalize() method that uncapitalizes all the whitespace-separated words in a String. You should use this method if and only if you need to do lowercase of each word in a string.

Download Code

 
All methods in the WordUtils class handles null strings gracefully. To capitalize all the whitespace-separated words, use WordUtils.capitalizeFully() method. It converts each word in the string to a title case character, followed by all lowercase characters.

Download Code

That’s all about converting a String to uppercase and lowercase in Java.