JAVA program to convert a string from uppercase to lowercase

JAVA program to convert a string from uppercase to lowercase

This JAVA program is to convert a string from uppercase to lowercase.

For example, if the given string is HELLO WORLD(uppercase) then the string will be converted to hello world(lowercase).

Logic

We iterate till the length of the string and check for small case characters.If we find an uppercase character then we know that ASCII value of ‘A’ is 65 and that of ‘a’ is 97, so the difference between uppercase and lowercase is 32 so we add 32 to the uppercase character.

Dry Run of the Program

Take input string ‘st’. Let us take st=CODE

Convert string to char array ‘str’

1st iteration for(i=0;i<str.length;i++)  i.e. for(i=0;0<4;i++)

if(str[i]>=’A’ && str[i]<=’Z’)  i.e. if(str[0]>=’A’ && str[0]<=’Z’) hence(‘C’>=’A’ && ‘C'<=’Z’) true

str[i]=str[i]+32;  i.e.  str[0]=str[0]+32;  i.e. str[o]=67+32;  hence str[0]=99 hence str[0]=’c’

2nd iteration for(i=1;i<str.length;i++)  i.e. for(i=1;1<4;i++)

if(str[i]>=’A’ && str[i]<=’Z’)  i.e. if(str[1]>=’A’ && str[1]<=’Z’) hence(‘O’>=’A’ && ‘O'<=’Z’) true    

str[i]=str[i]+32;  i.e.  str[1]=str[1]+32;  i.e. str[1]=  79+32;  hence str[1]=111 hence str[1]=’o’

3rd iteration for(i=2;i<str.length;i++)  i.e. for(i=2;2<4;i++)

if(str[i]>=’A’ && str[i]<=’Z’)  i.e. if(str[2]>=’A’ && str[2]<=’Z’) hence(‘D’>=’A’ && ‘D'<=’Z’) true

str[i]=str[i]+32;  i.e.  str[2]=str[2]+32;  i.e. str[2]=  68+32;  hence str[1]=100 hence str[2]=’d’

4th iteration for(i=3;i<str.length;i++)  i.e. for(i=3;3<4;i++)

if(str[i]>=’A’ && str[i]<=’Z’)  i.e. if(str[1]>=’A’ && str[1]<=’Z’) hence(‘E’>=’A’ && ‘E'<=’Z’) true

str[i]=str[i]+32;  i.e.  str[3]=str[3]+32;  i.e. str[3]=69+32;  hence str[0]=101 hence str[3]=’e’

For Loop ends here as i=4 which is not less than 4.

So the output printed is ‘code’.

Program

import java.util.*;

class upperLower
{
	public static void main(String args[])
	{
    		String st;
		int i;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter any string which is to be converted to lowercase");
	 	st=sc.nextLine();
		char str[]=st.toCharArray();
    		for(i=0;i<str.length;i++)
    		{
        		if(str[i]>='A' && str[i]<='Z')
        		{ 
        			str[i]=(char)((int)str[i]+32);
        		}
    		}
    		System.out.println("The string in LowerCase is");
		for(i=0;i<str.length;i++)
    			System.out.print(str[i]);
	}
}

Output

Share Me!