Change Case of String Characters in Java

In this article we are going to learn how to write a java program to change lower case characters of a string with upper case and vice-versa.

Here, we traverse the complete string and look for each character and if the character is in lower case, we make it to upper case and vice versa by using java built-in methods i.e., toUpperCase() and toLoweCase().

Example

If the input is “My Code” then the output will be “mY cODE”.

If the input is “Lower Case” then the output will be “lOWER cASE”.

Java Program to change the case of string characters.

public class StringCharacters {

        public static void main(String[] args) {
            String s="The Code Data";
         StringCharacters tcd=new StringCharacters();

            //changeCase method change the lower case string characters to upper case and vice-versa
            tcd.changeCase(s);
        }
        public void changeCase(String s) {
            StringBuffer str=new StringBuffer(s);
            for(int i=0;i<s.length();i++) {
                if(Character.isLowerCase(s.charAt(i))) {
                    str.setCharAt(i, Character.toUpperCase(s.charAt(i)));
                }
                else if(Character.isUpperCase(s.charAt(i))) {
                    str.setCharAt(i, Character.toLowerCase(s.charAt(i)));
                }
            }
            System.out.println("The new String after case conversion is: "+str);
        }

    }

Change case of string characters in Java

We can also code the same program to change all the lower-case characters of a string to uppercase and upper-case characters to lowercase in other languages like C, C++, Python, etc

Similar Java Tutorials

Leave a Comment