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:
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:
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:
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.