Java String to Uppercase | DigitalOcean

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java String to uppercase conversion can be done using toUpperCase() method.

Java String to UpperCase

java string to uppercase

  • Java String toUpperCase() method has two variants – toUpperCase() and toUpperCase(Locale locale).
  • Conversion of the characters to upper case is done by using the rules of default locale. Calling toUpperCase() function is same as calling toUpperCase(Locale.getDefault()).
  • Java String to upper case method is locale sensitive, so use it carefully with strings that are intended to be used locale independent. For example programming language identifiers, HTML tags, protocol keys etc. Otherwise you might get unwanted results.
  • To get correct upper case results for locale insensitive strings, use toUpperCase(Locale.ROOT) method.
  • String toUpperCase() returns a new string, so you will have to assign that to another string. The original string remains unchanged because String is immutable.
  • If locale is passed as null to toUpperCase(Locale locale) method, then it will throw NullPointerException.

Java String to Uppercase Example

Let’s see a simple example to convert a string to upper case and print it.

String str = "Hello World!";
System.out.println(str.toUpperCase()); //prints "HELLO WORLD!"

We can also use Scanner class to get user input and then convert it to uppercase and print it. Here is a complete example program to convert java string to uppercase and print it.

package com.journaldev.string;

import java.util.Scanner;

public class JavaStringToUpperCase {

	public static void main(String[] args) {
		String str = "hello World!";

		String strUpperCase = str.toUpperCase();

		System.out.println("Java String to Upper Case: " + strUpperCase);

		readUserInputAndPrintInUpperCase();
	}

	private static void readUserInputAndPrintInUpperCase() {
		Scanner sc = new Scanner(System.in);
		System.out.println("Please write input String and press Enter:");
		String str = sc.nextLine();
		System.out.println("Input String in Upper Case = " + str.toUpperCase());
		sc.close();
	}

}

Below console output shows the sample execution of above program.

Java String to Upper Case: HELLO WORLD!
Please write input String and press Enter:
Welcome to JournalDev Tutorials
Input String in Upper Case = WELCOME TO JOURNALDEV TUTORIALS

That’s all for java string to uppercase conversion example. Reference: API Doc