Java String Case Converter


 

Java String Case Converter

In this section, you will learn how to convert lowercase characters to upper case and upper case characters to lower case simultaneously from the given input string.

In this section, you will learn how to convert lowercase characters to upper case and upper case characters to lower case simultaneously from the given input string.

Java String Case Converter

Here we are going to convert lowercase characters to upper case and upper case characters to lower case simultaneously from the given input string.

Description of code:

Through the following code, we have allowed the user to input string of their choice and create an object of StringBuffer. The string is then converted into character array. Then, using for loop, we  iterate throughout the character array and check if there is space then this space should append as it is in the StringBuffer object. If there is a lowercase character then convert it into uppercase using Character.toUpperCase(ch[i]) which is then appended to buffer object and if there is a uppercase character then convert it into lowercase using Character.toLowerCase(ch[i]) and append it to the buffer object. Now, the StringBuffer object holds the converted string. This object is then converted into string and display the result.

Here is the code:

import java.util.*;

class CaseConverter {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("Enter string: ");
		String str = input.nextLine();
		StringBuffer sb = new StringBuffer();
		char ch[] = str.toCharArray();
		for (int i = 0; i < ch.length; i++) {
			if (ch[i] == ' ') {
				sb.append(" ");
			}
			if (Character.isLowerCase(ch[i])) {
				char cha = Character.toUpperCase(ch[i]);
				sb.append(Character.toString(cha));
			} else if (Character.isUpperCase(ch[i])) {
				char cha = Character.toLowerCase(ch[i]);
				sb.append(Character.toString(cha));
			}
		}
		System.out.println(sb.toString() + " ");
	}
}

Output:

Enter string: HeLLo WoRLD
hEllO wOrld

Ads