Frequently Asked Java Program 36 : Java Program to Invert Case of Each Char in a String

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program to invert the case of each character of string.


Input: – mAkE SeleNIUM eaSY

Output:-MaKe sELEnium EAsy

Let’s start with the logic:-

  1. Iterate entire string char by char.
  2. Check if current char is in uppercase or Lowercase. We can use isUpperCase(Character char) and isLowerCase(Character char) methods of Character class. These methods return boolean value. We can also use ASCII concept as well. In this post, we will use methods of Character class.
  3. Once we find the case type of current character, we can use toUpperCase(Character c) and toLowerCase(Character c) methods of Character class to invert the case and replace the content of char array at given index.
  4. To convert a char array to string again, we can use overloaded constructor of String class which takes char[] as argument.

Java Program:-

package StringPrograms;

import java.util.Arrays;
import java.util.Scanner;

public class InvertCaseOfChar {
	// Method to invert the case
	public static String invertCaseOfString(String input)
		// Converting string to char array
		char[] charsInput = input.toCharArray();
		// Iterating each char of string
		for(int i =0; i< charsInput.length ; i++)
			// Check if current char is uppercase. Note it will give false for numbers and special chars.
				// If upper case, convert to lowercase
				charsInput[i] = Character.toLowerCase(charsInput[i]);
				// If not uppercase, it will be changed to lowercase. 
				// If we add another if condition to check if char is lowercase, that will make program
				// more optimal.
				charsInput[i] = Character.toUpperCase(charsInput[i]);				
// Converting char array to string		
return new String(charsInput);
	public static void main(String[] args) {
		// Taking input as String
		Scanner sc = new Scanner(;
		System.out.println("Enter string to invert the case:- ");
		String inputString = sc.nextLine();
		System.out.println("Input stirng : "+inputString);
		System.out.println("Output string : "+invertCaseOfString(inputString));



You can run above program for multiple inputs and if it fails for any condition, let me know.


Leave a Reply

Your email address will not be published. Required fields are marked *