Dremendo Tag Line

Input sentence and convert capital letters to small and vice versa in Java

String - Question 7

In this question, we will see how to input a sentence and convert all the capital letters to small letters and vice versa in Java programming. To know more about string click on the string lesson.

Q7) Write a program in Java to input a sentence and convert all the capital letters to small letters and vice versa.

Program

import java.util.Scanner;

public class Q7
{
    public static void main(String args[])
    {
        String s;
        char ca[];		// declared a character array
        int i;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a sentence");
        s=sc.nextLine();
        ca=s.toCharArray();   // store the string into the character array
        for(i=0; i<ca.length; i++)
        {
            // check if the character is an alphabet
            if(Character.isAlphabetic(ca[i])==true)
            {
                if(Character.isUpperCase(ca[i])==true)
                {
                    // change the character to lowercase if uppercase
                    ca[i]=Character.toLowerCase(ca[i]);
                }
                else if(Character.isLowerCase(ca[i])==true)
                {
                    // change the character to uppercase if lowercase
                    ca[i]=Character.toUpperCase(ca[i]);
                }
            }
        }

        //printing the character array
        for(i=0; i<ca.length; i++)
        {
            System.out.print(ca[i]);
        }
    }
}

Output

Enter a sentence
We arE LiVinG in A DemocraTiC CounTRY
wE ARe lIvINg IN a dEMOCRAtIc cOUNtry
video-poster