JAVA program to toggle all characters of a string

JAVA program to toggle characters of a string

This JAVA program is to toggle characters of a string. That means that if a character is in lowercase then it will be converted(toggled) to uppercase and vice versa.

For example, JuSt CoDe will be toggled to jUsT cOdE.

Logic

We just use a simple logic that is we know lowercase letter ‘a’ starts from 97 and uppercase letter ‘A’ starts from 65.So if we want to convert from lowercase to uppercase then we subtract 32(92-65=32) and add 32 to convert a character from uppercase to lowercase.

Dry Run of the Program

Take input string ‘str’. Let us take str=cODE

Convert string to char array ‘a[]’

1st iteration for(c=0;c<a.length;c++)  i.e. for(c=0;c<a.length;c++)

if(a[c]>=’A’ && a[c]<=’Z’)  i.e.  if(a[0]>=’A’ && a[0]<=’Z’) false as a[0]=’c’ ASCII VALUE of ‘c’=99 so we go to else if

else if(a[c]>=’a’ && a[c]<=’z’) i.e. else if(a[0]>=’a’ && a[0]<=’z’) true so execute statement inisde else if

a[c]=a[c]-32; i.e. a[0]=a[0]-32; i.e. a[0]=99-32; a[0]=67  ASCII VALUE OF ‘C’ =67

2nd iteration for(c=1;c<a.length;c++)  i.e. for(c=1;c<a.length;c++)

if(a[c]>=’A’ && a[c]<=’Z’)  i.e.  if(a[1]>=’A’ && a[1]<=’Z’) true as a[1]=’O’ ASCII VALUE of ‘O’=79 so execute stmts

a[c]=a[c]+32; i.e. a[1]=a[1]+32; i.e. a[1]=79+32; a[1]=111  ASCII VALUE OF ‘o’ =111

3rd iteration for(c=2;c<a.length;c++)  i.e. for(c=2;c<a.length;c++)

if(a[c]>=’A’ && a[c]<=’Z’)  i.e.  if(a[2]>=’A’ && a[2]<=’Z’) true as a[2]=’D’ ASCII VALUE of ‘D’=68 so execute stmts

a[c]=a[c]+32; i.e. a[2]=a[2]+32; i.e. a[2]=68+32; a[2]=100  ASCII VALUE OF ‘d’ =100

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

if(a[c]>=’A’ && a[c]<=’Z’)  i.e.  if(a[3]>=’A’ && a[3]<=’Z’) true as a[3]=’E’ ASCII VALUE of ‘E’=69 so execute stmts

a[c]=a[c]+32; i.e. a[3]=a[3]+32; i.e. a[3]=69+32; a[3]=101  ASCII VALUE OF ‘e’ =101

For Loop ends here as i(4) is greater than 3.

We print the output of the toggled string as Code

Progam

import java.util.*;

class toggle
{
	public static void main(String args[])
	{
    		int c;
		String str;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the string to be toggled");
	 	str=sc.nextLine();
		char a[]=str.toCharArray();
    		for(c=0;c<a.length;c++)
    		{
        		if(a[c]>='A' && a[c]<='Z')
        		{
            			a[c]=(char)((int)a[c]+32);
        		}
        		else if(a[c]>='a' && a[c]<='z')
        		{
            			a[c]=(char)((int)a[c]-32);
        		}
    		}
      		System.out.println("The toggled string is :-");
		for(c=0;c<a.length;c++)
    			System.out.print(a[c]);
	}
}

Output

Share Me!