Java String to LowerCase
- Java String
toLowerCase()
method has two variants –toLowerCase()
andtoLowerCase(Locale locale)
. - Conversion of the characters to lower case is done by using the rules of default locale. Calling
toLowerCase()
function is same as callingtoLowerCase(Locale.getDefault())
. - Java String to lower case method is locale sensitive, so use it carefully with strings that are intended to be used locale independently. For example programming language identifiers, HTML tags, protocol keys etc. Otherwise you might get unwanted results.
- To get correct lower case results for locale insensitive strings, use
toLowerCase(Locale.ROOT)
method. - String
toLowerCase()
returns a new string, so you will have to assign that to another string. The original string remains unchanged because Strings are immutable. - If locale is passed as
null
totoLowerCase(Locale locale)
method, then it will throw NullPointerException.
Java String to LowerCase Example
Let’s see a simple example to convert a string to lower case and print it.
1 2 3 4 |
String str = "Hello World!"; System.out.println(str.toLowerCase()); //prints "hello world!" |
We can also use Scanner class to get user input and then convert it to lower case and print it.
Here is a complete example program to convert java string to lowercase and print it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.journaldev.string; import java.util.Scanner; public class JavaStringToLowerCase { public static void main(String[] args) { String str = "JournalDev"; String strLowerCase = str.toLowerCase(); System.out.println("Java String to Lower Case Example Output: " + strLowerCase); readUserInputAndPrintInLowerCase(); } private static void readUserInputAndPrintInLowerCase() { Scanner sc = new Scanner(System.in); System.out.println("Please provide input String and press Enter:"); String str = sc.nextLine(); System.out.println("Input String in Lower Case = " + str.toLowerCase()); sc.close(); } } |
Below image shows the output from a sample execution of above program.
That’s all for java string to lowercase conversion example.
Reference: API Doc