Java Strings: Changing Case
Changing Case
There are a couple of options when it comes to changing the case of string in Java. We can change the case of an entire string to upper case using the toUpperCase() method. The general syntax is:
String.toUpperCase();
Similarly, we can change the case of an entire string to lower case using the toLowerCase() method. The general syntax is:
String.toLowerCase();
Let’s see this method in action by converting a string to uppercase and then to lowercase:
public static void main(String[] args){ String stringGreeting = "Hello everyone!"; //Printout the original string System.out.println(stringGreeting); //Convert the string to uppercase System.out.println(stringGreeting.toUpperCase()); //Convert the string to lowercase System.out.println(stringGreeting.toLowerCase()); //Convert the string back to uppercase System.out.println(stringGreeting.toUpperCase()); //Printout the original string to show it remains unchanged System.out.println(stringGreeting); }
The output returns the original and modified strings:
run: Hello everyone! HELLO EVERYONE! hello everyone! HELLO EVERYONE! Hello everyone! BUILD SUCCESSFUL (total time: 0 seconds)
Applying this method to a string does not alter the string, and we can see that in the output above.