×

Java Programs

Java Practice

Uppercase to lowercase conversion without using any library function in Java

Java uppercase to lowercase conversion: Here, we are going to learn how to convert uppercase string to lowercase without using any library function in Java?
Submitted by IncludeHelp, on July 12, 2019

Given a string and we have to convert it from uppercase to lowercase.

Examples:

    Input:
    IncludeHelp.com
    Output:
    includehelp.com

    Input:
    123ABCD@9081
    Output:
    123abcd@9081

Uppercase to lowercase conversion

To convert an uppercase alphabet to lowercase alphabet – we can add 32 in uppercase alphabet's ASCII code to make it a lowercase alphabet (because the difference between a lowercase alphabet ASCII and an uppercase alphabet ASCII is 32).

In the below code, we created a user-defined function UpperToLower() that will accept a string and returns string having lowercase characters. To convert uppercase alphabets of the string to lowercase alphabets, we are extracting characters one by one from the string using String.charAt() function and checking whether the character is an uppercase alphabet, if it is an uppercase alphabet, we are adding 32 to make it lowercase, else no change. Thus, only uppercase alphabets will be converted to lowercase alphabets, the rest of the characters like lowercase alphabets, digits and special characters will remain the same.

Java code for uppercase to lowercase conversion

// Uppercase to lowercase conversion without using 
// any library function in Java

public class Main {
    static String UpperToLower(String s) {
        String result = "";
        char ch = ' ';
        for (int i = 0; i < s.length(); i++) {
            
            //check valid alphabet and it is in Uppercase
            if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') {
                ch = (char)(s.charAt(i) + 32);
            }
            //else keep the same alphabet or any character
            else {
                ch = (char)(s.charAt(i));
            }
            
            result += ch; // concatenation, append c to result
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(UpperToLower("IncludeHelp.com"));
        System.out.println(UpperToLower("www.example.com"));
        System.out.println(UpperToLower("123ABCD@9081"));
        System.out.println(UpperToLower("OKAY@123"));        
    }
}

Output

includehelp.com
www.example.com
123abcd@9081
okay@123

Java String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.