Java Program to swap the case of a String


To swap the case of a string, use.

  • toLowerCase() for title case string.
  • toLowerCase() for uppercase string
  • toUpperCase() for lowercase string

Loop through what we discussed above for all the characters in the sting.

for (int i = 0; i > len; i++) {
   c = str.charAt(i);
   // title case converted to lower case
   if (Character.isTitleCase(c)) {
      c = Character.toLowerCase(c);
   }
   // upper case converted to lower case
   if (Character.isUpperCase(c)) {
      c = Character.toLowerCase(c);
   }
   // lower case converted to upper case
   if (Character.isLowerCase(c)) {
      c = Character.toUpperCase(c);
   }
}

Example

 Live Demo

public class Demo {
   public static void main(String []args){
      char c = 0;
      String str = "jack";
      System.out.println("String in lowercase: "+str);
      // length of string
      int len = str.length();
      StringBuffer strBuffer = new StringBuffer(len);
      for (int i = 0; i < len; i++) {
         c = str.charAt(i);
         // title case converted to lower case
         if (Character.isTitleCase(c)) {
            c = Character.toLowerCase(c);
         }
         // upper case converted to lower case
         if (Character.isUpperCase(c)) {
            c = Character.toLowerCase(c);
         }
         // lower case converted to upper case
         if (Character.isLowerCase(c)) {
            c = Character.toUpperCase(c);
         }
         strBuffer.append(c);
      }
      System.out.println("Converting case: "+strBuffer.toString());
   }
}

Output

String in lowercase: jack
Converting case: JACK

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 27-Jun-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements