April 1, 2022

Java String toLowerCase() And toUpperCase() Methods

In this post you’ll learn how to change case of the String in Java using toLowerCase() and toUpperCase() methods.

toLowerCase() method in Java String

  • String toLowerCase()- Used to convert all of the characters in this String to lower case. If no argument is passed then rules of the default locale is used, making it equivalent to calling toLowerCase(Locale.getDefault()). Note that this method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently.
  • String toLowerCase(Locale locale)- Converts all of the characters in this String to lower case using the rules of the given Locale.
public class StringCase {
  public static void main(String[] args) {
    String str = "TEST String";
    System.out.println("String converted in all lower case- " + str.toLowerCase());
  }
}
Output
String converted in all lower case- test string

Note that the modified string is a new String object which has to be assigned to a String object if you intend to store the modified String. This is because String is immutable in Java.

public class StringCase {
  public static void main(String[] args) {
    String str = "TEST String";
    System.out.println("String converted in all lower case- " + str.toLowerCase());
    System.out.println("Original String- " + str);
    // assigning modified string
    str = str.toLowerCase();
    System.out.println("Modified String- " + str);
  }
}
Output
String converted in all lower case- test string
Original String- TEST String
Modified String- test string

Here you can see initially original string remains intact even though toLowerCase() method is called on it. Once str is assigned the modified string then only it changes.

toUpperCase() method in Java String

  • String toUpperCase()- Used to convert all of the characters in this String to upper case. If no argument is passed then rules of the default locale is used, making it equivalent to calling toUpperCase(Locale.getDefault()). Note that this method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently.
  • String toUpperCase(Locale locale)- Converts all of the characters in this String to upper case using the rules of the given Locale.
public class StringCase {
  public static void main(String[] args) {
    String str = "Test String";
    System.out.println("String converted in all upper case- " + str.toUpperCase());
  }
}
Output
String converted in all upper case- TEST STRING

That's all for the topic Java String toLowerCase() And toUpperCase() Methods. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment