Java With Us
Home   |   Tutorial   |   Programs

Converting a String to different Cases - Upper Case, Lower Case, Toggle Case, Camel Case and Sentence Case

In this article, we will see how to convert a given String to different cases using simple looping and methods of the String class and the Character class. First, we clearly specify what these different cases are. Then, we move on to see the different methods of the Character and String class we would be using after which we proceed to the algorithms. Finally we present a complete program which takes a String input and outputs it in the five different cases.

The different cases

Upper Case : A String is converted to Upper Case by capitalizing each of the letters. Letters that are already capitalised are left as they are. Non letters like numbers and special characters are not altered.

Lower Case : The conversion of a String to lower case is similar to upper case except that we change each of the letter to its lower case form. Toggle Case : Small letters a-z are converted to capital letters A-Z and vice versa.

Camel Case: In Camel Case, the first letter of every word is capitalized.

Sentence Case: The starting letter of the first word of every sentence is capitalized.

Given below is an example illustrating the conversion of a String to the five different cases mentioned above.

HeLLo java. hello WORlD.
Upper Case: HELLO JAVA. HELLO WORLD.
Lower Case: hello java. hello world.
Toggle Case: hEllO JAVA. HELLO worLd.
Camel Case: Hello Java. Hello World.
Title Case: Hello java. Hello world.

Methods of String and Character classes

We would be using length() and charAt(int) methods of the String class. The length() method returns the numbers of characters that the String contains. The charAt() method takes an integer argument and returns the character contained at that integer index. It is to be noted that the indices begin from 0. The following code snippet illustrates the usage of these two methods.

String s = "Java";
int len = s.length(); // len = 4
char c0 = s.charAt(0); // c0 = 'J'
char c2 = s.charAt(2); // c2 = 'v'

The Character class contains a number of static methods which can be used to test whether a character is upper case or lower case and also convert between the two forms. The two methods isUpperCase(char) and isLowerCase(char) take a character as an argument and return a boolean value indicating whether the argument passed is an upper case char or a lower case char. The methods toUpperCase(char) and toLowerCase(char) take char arguments and return a char which is the upper case form and the lower case form of the passed char respectively. If the character passed is not a letter, the return value will be the same as the character passed. Here is a code snippet illustrating the use of the above stated methods.

boolean a = Character.isUpperCase('A'); // true
boolean b = Character.isLowerCase('A'); // false
boolean c = Character.isUpperCase('<'); // false
boolean d = Character.isLowerCase('<'); // false
char e = Character.toLowerCase('A'); // 'a'
char f = Character.toUpperCase('a'); // 'A'
char g = Character.toLowerCase('<'); // '<'
char h = Character.toLowerCase('a'); // 'a'

Converting a String to Upper Case

To convert a String to Upper Case, we use a for loop whose counter, say i, runs from 0 through the length of the String (-1). A String variable 'result' is initialised with an empty String. Within the loop, we extract the character at position i, convert it to an upper case character using the toUpperCase () method and append the returned char to the result. At the end of the loop, the result contains the input string with all characters changed to upper case. Scroll down to the bottom of this page to the method toUpperCase() to view the code.

Converting a String to Lower Case

This task would be similar to the above except that instead of using the method toUpperCase (), we use the method toLowerCase() to convert the characters to their lower case form.

Converting a String to Toggle Case

To convert the String to its toggle form, we extract each character as we have done for upper case conversion. We then use an if else decision making statement to check if the extracted character is upper case or lower case. If the character is upper case, we convert it to lower case and append it to the result. Otherwise, the upper case form of the character is appended to the result. View the code at the bottom of this page.

It should be noted that we cannot use an if else if statement decision making statement as shown below.

if (Character.isUpperCase(currentChar)) {
   ...
} else if (Character.isLowerCase(currentChar)) {
   ...
}

This is because there is a possibility for a character to be neither upper case nor lower case - digits and special symbols like < , > etc. If a decision making statement as shown above is used, these characters would be ignored.

Of course, a modified form of the above code can be used where we first check if the character is an upper case character. Then we check if it is a lower case character. And finally, if the character is neither an uppercase character nor a lower case character, we simply append it to the result without any conversions.

if (Character.isUpperCase(currentChar)) { // Upper Case
   char currentCharToLowerCase = Character.toLowerCase(currentChar);
   result = result + currentCharToLowerCase;
} else if (Character.isLowerCase(currentChar)) { // Lower Case
   char currentCharToUpperCase = Character.toUpperCase(currentChar);
   result = result + currentCharToUpperCase;
} else { // Not a letter
   result = result + currentChar;
}

Converting a String to Camel Case

As already said, in camel case, we capitalise the first letter of each word. To do so, we use a loop similar to what we have used in the previous conversions. Within the loop, we check if the character at index i-1 is a space. If it is so, we capitalise the current character at index i and append it to the result. Otherwise, we convert the current char to lower case and append it.

However, we will experience a problem when the loop counter i has the value of zero as accessing character at index (0-1) will result in an exception. To avoid this, before the loop, we check if the length of the input string is zero. If it is so, we simply return an empty String. Otherwise, we initialise the result with the capitalized version of the character at index zero and then start the loop from i = 1. The code is shown at the bottom of this page.

Converting a String to Sentence Case

In sentence case, the first letter of each sentence is capitalized. This conversion cannot be solved in a way similar to the camel case problem, replacing the space with a period. The reason is that a sentence does not always end in a period. Sentences also end with question marks and exclamation marks. The second reason is that the first letter of the sentence doesn't always immediately follow the period. In most cases, there is a space between the two.

To tackle the above problems, we maintain an array of terminal characters - the characters with which a sentence ends such as period, exclamation mark and question mark. We will also use a boolean variable 'terminalCharacterEncountered' which will be set to true whenever one of the terminal characters is encountered. Within the loop, we first extract a character, if the terminalCharacterEncountered flag is false, we simply append the character to the output String. If the flag was true, the current character is capitalized and appended to the result. And then, the flag is reset to false. After performing the above task, we check if the current character is one of the terminal characters. If so, the flag is set to true again so that the first character of the next sentence will be capitalised. The code is shown in the next section ( scroll down).

The Program

Given below is a complete program which takes an input String from the user, converts it into different cases and displays them on the console.

import java.util.Scanner;

public class CaseManipulation {

   public static String toUpperCase(String inputString) {
       String result = "";
       for (int i = 0; i < inputString.length(); i++) {
           char currentChar = inputString.charAt(i);
           char currentCharToUpperCase = Character.toUpperCase(currentChar);
           result = result + currentCharToUpperCase;
       }
       return result;
   }

   public static String toLowerCase(String inputString) {
       String result = "";
       for (int i = 0; i < inputString.length(); i++) {
           char currentChar = inputString.charAt(i);
           char currentCharToLowerCase = Character.toLowerCase(currentChar);
           result = result + currentCharToLowerCase;
       }
       return result;
   }

   public static String toToggleCase(String inputString) {
       String result = "";
       for (int i = 0; i < inputString.length(); i++) {
           char currentChar = inputString.charAt(i);
           if (Character.isUpperCase(currentChar)) {
               char currentCharToLowerCase = Character.toLowerCase(currentChar);
               result = result + currentCharToLowerCase;
           } else {
               char currentCharToUpperCase = Character.toUpperCase(currentChar);
               result = result + currentCharToUpperCase;
           }
       }
       return result;
   }

   public static String toCamelCase(String inputString) {
       String result = "";
       if (inputString.length() == 0) {
           return result;
       }
       char firstChar = inputString.charAt(0);
       char firstCharToUpperCase = Character.toUpperCase(firstChar);
       result = result + firstCharToUpperCase;
       for (int i = 1; i < inputString.length(); i++) {
           char currentChar = inputString.charAt(i);
           char previousChar = inputString.charAt(i - 1);
           if (previousChar == ' ') {
               char currentCharToUpperCase = Character.toUpperCase(currentChar);
               result = result + currentCharToUpperCase;
           } else {
               char currentCharToLowerCase = Character.toLowerCase(currentChar);
               result = result + currentCharToLowerCase;
           }
       }
       return result;
   }

   public static String toSentenceCase(String inputString) {
       String result = "";
       if (inputString.length() == 0) {
           return result;
       }
       char firstChar = inputString.charAt(0);
       char firstCharToUpperCase = Character.toUpperCase(firstChar);
       result = result + firstCharToUpperCase;
       boolean terminalCharacterEncountered = false;
       char[] terminalCharacters = {'.', '?', '!'};
       for (int i = 1; i < inputString.length(); i++) {
           char currentChar = inputString.charAt(i);
           if (terminalCharacterEncountered) {
               if (currentChar == ' ') {
                   result = result + currentChar;
               } else {
                   char currentCharToUpperCase = Character.toUpperCase(currentChar);
                   result = result + currentCharToUpperCase;
                   terminalCharacterEncountered = false;
               }
           } else {
               char currentCharToLowerCase = Character.toLowerCase(currentChar);
               result = result + currentCharToLowerCase;
           }
           for (int j = 0; j < terminalCharacters.length; j++) {
               if (currentChar == terminalCharacters[j]) {
                   terminalCharacterEncountered = true;
                   break;
               }
           }
       }
       return result;
   }

   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       System.out.print("Enter an input String: ");
       String inputString = scanner.nextLine();
       System.out.println("Upper Case: " + toUpperCase(inputString));
       System.out.println("Lower Case: " + toLowerCase(inputString));
       System.out.println("Toggle Case: " + toToggleCase(inputString));
       System.out.println("Camel Case: " + toCamelCase(inputString));
       System.out.println("Title Case: " + toSentenceCase(inputString));
   }
}

Privacy Policy