Java String toLowerCase() example

In this guide, you will learn about the String toLowerCase() method in Java programming and how to use it with an example.

1. String toLowerCase() Method Overview

Definition:

The toLowerCase() method of Java's String class converts all the characters in the given string to lowercase using the rules of the default locale.

Syntax:

1. str.toLowerCase()
2. str.toLowerCase(Locale locale)

Parameters:

- locale: The locale object represents a specific geographical, political, or cultural region. This is an optional parameter, and if not provided, the method uses the default locale.

Key Points:

- The method returns a newly allocated string, leaving the original string unaffected.

- It's vital to note that case conversions might not always be one-to-one. For instance, certain Unicode characters convert into multiple characters in lowercase.

- Using the variant with a Locale can be essential for languages where character conversion depends on cultural rules.

2. String toLowerCase() Method Example

import java.util.Locale;

public class ToLowerCaseExample {
    public static void main(String[] args) {
        String sample1 = "JavaPROGRAMMING";

        // Convert entire string to lower case
        String lower1 = sample1.toLowerCase();
        System.out.println("Lowercase of 'JavaPROGRAMMING': " + lower1);

        // Demonstrate the importance of locale
        String sample2 = "I\u0307";  // String composed of "I" and a combining dot above
        System.out.println("Default toLowerCase: " + sample2.toLowerCase());
        System.out.println("Turkish locale toLowerCase: " + sample2.toLowerCase(new Locale("tr", "TR")));
    }
}

Output:

Lowercase of 'JavaPROGRAMMING': javaprogramming
Default toLowerCase: i̇
Turkish locale toLowerCase: i

Explanation:

In the example:

1. The first usage of toLowerCase() converts the string "JavaPROGRAMMING" to "javaprogramming".

2. The second part of the example demonstrates the importance of locale. The default conversion of the Unicode character "I" with a dot above retains the dot in its lowercase form. However, in the Turkish locale, "I" converts to "i" without the dot.

Related Java String Class method examples

Comments