Java

How to Use Java String toLowerCase() Method?

In Java, the toLowerCase() method is a String class function that returns a new string with all the original string’s characters transformed to lowercase. It does not change the actual string and returns a modified string having all lowercase characters. This article will illustrate the toLowerCase() method with practical implementation.

How to Use Java String toLowerCase() Method?

The Java String toLowerCase() function lowercases all characters in a provided string. This method is useful when users want to perform case-insensitive string comparisons or need to standardize the case of strings in the program.

Here is the basic syntax of the toLowerCase() method:

public String toLowerCase()

Here are a few examples of how users can use the toLowerCase() method in Java:

Example 1: Converting a String to Lowercase

Here is an example of using the toLowerCase() method for converting a string to lowercase in Java:

class HelloWorld {
    public static void main(String[] args) {
        String str = "Hello, World!";
        String lowerStr = str.toLowerCase();
        System.out.println(lowerStr);
    }
}

The description of the example is given below:

  • The toLowerCase() method is called on the str string object, which returns a new string with all the characters in str converted to lowercase.
  • The resulting string is saved in the lowerStr variable and then displayed to the console with System.out.println().

The output shows that a string has been converted to lowercase.

Example 2: Comparing Strings in a Case-Insensitive Manner

Another example is considered to compare strings in a case-insensitive manner:

class HelloWorld {
    public static void main(String[] args) {
String str1 = "HELLO";
String str2 = "hello";
if(str1.toLowerCase().equals(str2.toLowerCase())) {
    System.out.println("The two strings are equal (case-insensitive)");
} else {
    System.out.println("The two strings are not equal (case-insensitive)");
}
    }
}

In this example,

  • The toLowerCase() method is used to convert both str1 and str2 strings to lowercase before comparing them using the equals() method.
  • Since the comparison is done in a case-insensitive manner, the strings are considered equal and the first message is printed to the console.

In the above display, the output shows that the string “HELLO” is equal to “hello”.

Conclusion

In Java, the toLowerCase() method transforms all the characters in a provided string to lowercase. It returns a modified string having all lowercase characters, without altering the actual string. The method can be called on any string variable and takes no arguments. This guide has explained all examples to use the Java string toLowerCase() method.

About the author

Syed Minhal Abbas

I hold a master's degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.