Java String toUpperCase() example

In this guide, you will learn about the String toUpperCase() method in Java programming and how to use it with an example.

1. String toUpperCase() Method Overview

Definition:

The toUpperCase() method of Java's String class converts all the characters in the given string to upper case using the rules of the default locale.

Syntax:

1. str.toUpperCase()
2. str.toUpperCase(Locale locale)

Parameters:

- locale: The locale object represents a specific geographical, political, or cultural region. This is an optional parameter, and if not provided, the method uses the default locale.

Key Points:

- The method returns a newly allocated string, leaving the original string unaffected.

- Using the variant with a Locale can be essential for languages where character conversion depends on cultural rules.

2. String toUpperCase() Method Example

import java.util.Locale;

public class ToUpperCaseExample {
    public static void main(String[] args) {
        String sample1 = "JavaProgramming";

        // Convert entire string to upper case
        String upper1 = sample1.toUpperCase();
        System.out.println("Uppercase of 'JavaProgramming': " + upper1);

        // Demonstrate the importance of locale
        String sample2 = "i";
        System.out.println("Default toUpperCase: " + sample2.toUpperCase());
        System.out.println("Turkish locale toUpperCase: " + sample2.toUpperCase(new Locale("tr", "TR")));
    }
}

Output:

Uppercase of 'JavaProgramming': JAVAPROGRAMMING
Default toUpperCase: I
Turkish locale toUpperCase: Ä°

Explanation:

In the example:

1. The first usage of toUpperCase() converts the string "JavaProgramming" to "JAVAPROGRAMMING".

2. The second part of the example demonstrates the importance of locale. While the default conversion of the character "i" is "I", in the Turkish locale, "i" converts to "Ä°" (capital I with a dot).

Related Java String Class method examples

Comments