In this article we are going to learn how to write a java program to change lower case characters of a string with upper case and vice-versa.
Here, we traverse the complete string and look for each character and if the character is in lower case, we make it to upper case and vice versa by using java built-in methods i.e., toUpperCase() and toLoweCase().
Example
If the input is “My Code” then the output will be “mY cODE”.
If the input is “Lower Case” then the output will be “lOWER cASE”.
Java Program to change the case of string characters.
public class StringCharacters {
public static void main(String[] args) {
String s="The Code Data";
StringCharacters tcd=new StringCharacters();
//changeCase method change the lower case string characters to upper case and vice-versa
tcd.changeCase(s);
}
public void changeCase(String s) {
StringBuffer str=new StringBuffer(s);
for(int i=0;i<s.length();i++) {
if(Character.isLowerCase(s.charAt(i))) {
str.setCharAt(i, Character.toUpperCase(s.charAt(i)));
}
else if(Character.isUpperCase(s.charAt(i))) {
str.setCharAt(i, Character.toLowerCase(s.charAt(i)));
}
}
System.out.println("The new String after case conversion is: "+str);
}
}
We can also code the same program to change all the lower-case characters of a string to uppercase and upper-case characters to lowercase in other languages like C, C++, Python, etc
Similar Java Tutorials
- Odd Even in Java
- Method to print exception information in Java
- Exception Handling by Using try-catch in Java
- Checked Exception vs Unchecked Exception
- Exception Hierarchy in Java
- Java Exception Handling Interview Questions
- final finally finalize in java
- User Defined Exception in Java
- Exception Handling Keyword in Java
- throw throws in Java
- try with multiple catch block in Java
- Threads in Java
- Thread priority in Java