This Java example shows how to convert String to uppercase or lowercase using toUpperCase()
and toLowerCase()
methods of the String class as well as by using Apache Commons.
How to check if the String is in uppercase?
How to check if the String is in lowercase?
How to convert String to uppercase?
To convert string to the upper case, use the toUpperCase()
method of the Java String class.
1 |
pubic String toUpperCase() |
This method converts all the characters of a string to upper case using the default locale. Internally it is same as calling the toUpperCase(Locale.getDefault())
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class StringChangeCaseExample { public static void main(String[] args) { String str = "Hello World"; /* * To convert String to uppercase, use * toUpperCase() method of String class. */ System.out.println( "String to Upper Case: " + str.toUpperCase() ); } } |
Output
1 |
String to Upper Case: HELLO WORLD |
Using the Apache Commons Library
If you are using the Apache Commons library in your project, you can use the upperCase
method of the StringUtils class to change case of a string to upper case.
1 2 |
String str = "Hello World"; System.out.println( StringUtils.upperCase(str) ); |
How to convert String to lowercase?
To convert string to lower case, use the toLowerCase()
method of the String class.
1 |
pubic String toLowerCase() |
This method converts all the characters of a string to lower case using the default locale. Internally it is same as calling the toLowerCase(Locale.getDefault())
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.javacodeexamples.stringexamples; public class StringChangeCaseExample { public static void main(String[] args) { String str = "HeLLo WoRlD"; /* * To convert String to lowercase, use * toLowerCase() method of String class. */ System.out.println( "String to Lower Case: " + str.toLowerCase() ); } } |
Output
1 |
String to Lower Case: hello world |
Using the Apache Commons Library
If you are using the Apache Commons library in your project, you can use the lowerCase
method of the StringUtils class to change case of a string to lower case.
1 2 |
String str = "HeLLo WoRlD"; System.out.println( StringUtils.lowerCase(str) ); |
Important Note:
Both the toUpperCase()
and toLowerCase()
methods are locale sensitive. It could produce unexpected results if used on the strings which are intended to be interpreted locale independently.
If you are working with the string values which are locale insensitive, you should use the toUpperCase(Locale locale)
or toLowerCase(Locale locale)
methods instead.
This example is a part of the Java String tutorial.
Please let me know your views in the comments section below.