Java Program to swap the case of a String

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 14-Dec-2018 06:51:18
Advertisements