dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Jun 23, 2021

Java String Methods toUpperCase() and toLowerCase()

Converting a String to uppercase or lowercase in Java is fairly simply, thanks to a couple of built-in String methods that allow for such functionality. We will be looking at each of these methods - namely, the toUpperCase() and the toLowerCase() methods - in Java and learn how to properly use them.

Convert Strings to Uppercase in Java

To convert a string to all uppercase letters (for example: change james to JAMES), we use the Java String method, toUpperCase(). Here is some sample code to show how to do so:

 
public class Main {
  public static void main(String[] args) {
// Define a String
            	String superDuper = "super james";
// Print the String in its normal state
            	System.out.println(superDuper);
// Print the String in all Upper Case	
    System.out.println(superDuper.toUpperCase());
// Print out the String again to show no change
    System.out.println(superDuper);
  }
}

In the above code, we create a String and assign it a lowercase value of "super james". Then we print out the String to show how it looks prior to converting it to uppercase. Next, we apply the toUpperCase() method to our String and print it out, showing the conversion to all uppercase. Finally, we print the String one final time to show that the value of our String remains unchanged and still, technically, equals "super james".

Here is the output of the above code:

super james
SUPER JAMES
super james

Convert Strings to Lowercase in Java

On the flip side of this, it is just as easy to convert uppercase to lowercase text using the String method toLowerCase. For instance, you could change "JAMES" to "james" using the method. Here is an example showing how to change Strings to lowercase in Java:

 
public class Main {
  public static void main(String[] args) {
// Define a String
            	String superDuper = "Super James";
// Print the String in its normal state
            	System.out.println(superDuper);
// Print the String in all lowercase	
    System.out.println(superDuper.toLowerCase());
// Print out the String again to show no change
    System.out.println(superDuper);
  }
}

The output for this, as you might expect by now, would be:

Super James
super james
Super James

As with toUpperCase(), the method toLowerCase() does not permanently change the value of a String.

James Payne
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date