How to convert Uppercase String to Lowercase in Java

Hi coders! In this tutorial, we are going to see String class of Java. Our task is to convert uppercase String to lowercase in Java, for this we are going to use the StringBuffer class of Java and its functions.

StringBuffer is a  peer class of String that represents writable character sequences. In StringBuffer, we can add characters or substrings in the middle of a string or can be appended in the end.

Some of the functions of StringBuffer in Java are:

  • capacity() and length(): length() tells the length of the string and capacity() tells the total allocation.
  • insert(): To insert at the specific index. e.g.  StringBuffer insert(int index, String str)
  • append(): It is used to add text in the end, e.g. StringBuffer append(String str)
  • reverse(): It is used to reverse the string.
  • replace(): It is used to replace the text with new text.

Since we know that the ASCII value of A-Z is (65 to 90) and of a-z is (97 to 122).

So to convert from uppercase to lowercase we have to add 32 to every letter.

Steps to convert uppercase String to lowercase

  • Traverse the string one by one.
  • Check for every element of string, if found uppercase then convert it to lowercase.
  • Since we have a function called “toLowerCase” that converts uppercase to lowercase. Hence, we are using it.
  • Print the string.

Code to convert uppercase letters to lowercase letters in Java

public class Conversion {
  /* function to convert uppercase to loowercase*/
   static void upperToLower(StringBuffer str) 
     { 
        int l = str.length(); 
             
      
        for (int i=0; i<l; i++) 
        { 
           Character ch = str.charAt(i); /*traversing String one by one*/
            if (Character.isUpperCase(ch)) 
                str.replace(i, i+1, Character.toLowerCase(ch)+""); 
             
        } 
     } 
       
  public static void main(String[] args) {
   StringBuffer string = new StringBuffer("CODESPEEDY"); 
         
         upperToLower(string); 
           
         System.out.println(string); 
    
       
  }
  
  }
// Code is provided by Anubhav Srivastava
Output:

codespeedy

Hence, we have used predefined function “replace()”  and  “toLowerCase()” in this solution.

Hope you like the solution.

Also, read:

Convert array elements to camel case in Java
How To Get Date without Time in Java

Leave a Reply

Your email address will not be published. Required fields are marked *