JAVA program to convert a string from lowercase to uppercase without using string method

JAVA program to convert a string from lowercase to uppercase without using string method

This JAVA program is to convert a string from lowercase to uppercase without using string method

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

Logic

We iterate till the length of the string and check for small case characters. If we find a small case character then we know that ASCII value of ‘a’ is 97 and that of ‘A’ is 65, so the difference between uppercase and lowercase is 32 so we subtract 32 from the lowercase 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]=99-32;  hence str[0]=67 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]=  111-32;  hence str[1]=79 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]=  100-32;  hence str[1]=68 hence str[2]=’D’

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

if(str[i]>=’a’ && str[i]<=’z’)  i.e. if(str[3]>=’a’ && str[3]<=’z’) hence(‘e’>=’a’ && ‘e'<=’z’) true

str[i]=str[i]-32;  i.e.  str[3]=str[3]-32;  i.e. str[3]=101-32;  hence str[0]=69 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 lowerUpper
{
	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 uppercase");
	 	st=sc.nextLine();
		char str[]=st.toCharArray();
		System.out.println(str.length);
		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 UpperCase is");
		for(i=0;i<str.length;i++)
    			System.out.print(str[i]);
	}
}

Output

Share Me!