Convert a String to uppercase and lowercase in Java
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.
|
1 2 3 4 5 6 7 8 |
public class Main { public static void main(String[] args) { String s = "Hi"; System.out.println(s.toLowerCase()); // hi } } |
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.
|
1 2 3 4 5 6 7 8 9 10 |
import java.util.Locale; public class Main { public static void main(String[] args) { String s = "Hi"; System.out.println(s.toLowerCase(Locale.ENGLISH)); // hi } } |
To convert a string to uppercase, the String class provides a similar method toUpperCase():
|
1 2 3 4 5 6 7 8 |
public class Main { public static void main(String[] args) { String s = "hi"; System.out.println(s.toUpperCase()); // Hi } } |
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.
|
1 2 3 4 5 6 7 8 9 10 |
import org.apache.commons.text.WordUtils; public class Main { public static void main(String[] args) { String s = "Hello World"; System.out.println(WordUtils.uncapitalize(s)); // hello world } } |
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.
|
1 2 3 4 5 6 7 8 9 10 |
import org.apache.commons.text.WordUtils; public class Main { public static void main(String[] args) { String s = "hello world"; System.out.println(WordUtils.capitalizeFully(s)); // Hello World } } |
That’s all about converting a String to uppercase and lowercase in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)