Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Character.toUpperCase(char): uppercase one UTF-16 code unit

This method returns a single `char`. Use it to uppercase the first UTF-16 code unit of a string, not to uppercase an arbitrary Unicode code point or a whole grapheme.

Version: Java SE 21

Syntax

public static char toUpperCase(char ch)

In Java SE 21, Character.toUpperCase(char) is a static method on java.lang.Character. It takes one 16-bit UTF-16 code unit and returns one char: its uppercase equivalent if that mapping exists, or the original value otherwise. The method does not use locale rules and cannot return multiple characters.

For a non-empty string, text.charAt(0) reads the first code unit, so Character.toUpperCase(text.charAt(0)) selects the char overload. The + operator concatenates the result with the rest of the string from text.substring(1). Check text.isEmpty() first: charAt(0) on an empty string throws IndexOutOfBoundsException.

A supplementary Unicode code point takes two UTF-16 code units (a surrogate pair), and charAt(0) can return only the first of them. To uppercase one code point, use text.codePointAt(0) and Character.toUpperCase(int). This overload handles supplementary code points but still returns just one code point. An extended grapheme cluster, such as a letter followed by a combining accent, can span several code points. If the operation must cover the whole cluster, find its boundary first, for example with the regex \X.

To uppercase the whole string, use String.toUpperCase(Locale): choose the locale for the language, or Locale.ROOT for language-neutral text. The no-argument version uses the default locale. The result can change length: for example, ß can become SS.

Examples

import java.util.Locale;

public class Main {
    static String uppercaseFirstCodeUnit(String text) {
        if (text.isEmpty()) {
            return text;
        }
        return Character.toUpperCase(text.charAt(0)) + text.substring(1);
    }

    public static void main(String[] args) {
        System.out.println(uppercaseFirstCodeUnit("hello"));

        String deseret = "\uD801\uDC28"; // U+10428
        int afterChar = uppercaseFirstCodeUnit(deseret).codePointAt(0);
        int afterCodePoint = Character.toUpperCase(deseret.codePointAt(0));
        System.out.printf(Locale.ROOT, "char: U+%X%nint: U+%X%n", afterChar, afterCodePoint);
    }
}

Result

Hello
char: U+10428
int: U+10400

For `hello`, only the initial `h` changes. For the Deseret letter, the `char` overload leaves U+10428 unchanged, while the `int` overload returns its uppercase counterpart U+10400. Hexadecimal output does not require the console to render Deseret glyphs.

Related lessons

  • Java · Lesson 1 · Intermediate · Version: 2

Sources