Characters in a String

A Java String is a sequence of 16-bit char values, which is not quite the same as a sequence of characters. This page explains chars, code points and graphemes, then reads characters with charAt, toCharArray, chars() and codePoints(), classifies them with Character, shows the case-mapping and accent traps, and compares the speed of each way of looping.

Contents

chars, code points and graphemes

Three different things are called a "character", and the String API uses all of them:

  • A char is a 16-bit UTF-16 code unit, an unsigned number from 0 to 65,535. length(), charAt and every index in the String API count chars.
  • A code point is the number Unicode assigns to a character, from U+0000 to U+10FFFF. Code points up to U+FFFF, the Basic Multilingual Plane (BMP), fit in one char. Higher ones, which include most emoji, many musical and mathematical symbols and rare CJK ideographs, are stored as two chars called a surrogate pair: a high surrogate (U+D800 to U+DBFF) followed by a low one (U+DC00 to U+DFFF).
  • A grapheme cluster is what a reader sees as one character. It can be several code points: a letter followed by a combining accent, or a flag made of two regional indicator symbols.

For English text all three are the same, which is why code that confuses them often passes its tests. Java chose 16-bit chars in 1996, when Unicode still fitted in 16 bits; code point methods were added in Java 5 when Unicode outgrew that.

APIs for reading characters
APISinceWorks withBest for
charAt(i), length()Java 1.0charsIndex loops, ASCII and BMP text
toCharArray(), getCharsJava 1.0A copy of the charsSorting or editing characters
chars()Java 8IntStream of charsStream pipelines over BMP text
codePoints()Java 8IntStream of code pointsStream pipelines over any text
codePointAt, codePointCount, offsetByCodePointsJava 5Code pointsIndex loops over any text
Character.isLetter(int) and friendsJava 5 (int overloads)Code pointsClassifying characters
Character.toString(int), getNameJava 11, Java 7Code pointsPrinting and debugging
BreakIterator, regex \XJava 1.1, Java 9Grapheme clustersCounting or cutting what users see

The programs were compiled and run on JDK 21 with -Dstdout.encoding=UTF-8.

Reading chars: charAt and toCharArray

For simple text, charAt and toCharArray are all you need. A six-letter word keeps the indexes easy to follow, and the second half shows that a char is a number.

Java
import java.util.Arrays;

public class CharAccess {

    public static void main(String[] args) {
        String word = "Kotlin";

        char first = word.charAt(0);
        char last = word.charAt(word.length() - 1);
        System.out.println("first = " + first + ", last = " + last);

        // Loop by index
        StringBuilder spaced = new StringBuilder();
        for (int i = 0; i < word.length(); i++) {
            spaced.append(word.charAt(i)).append(' ');
        }
        System.out.println("spaced out: " + spaced.toString().strip());

        // toCharArray gives a copy you can change and sort
        char[] letters = word.toLowerCase().toCharArray();
        Arrays.sort(letters);
        System.out.println("sorted letters: " + new String(letters));
        System.out.println("original unchanged: " + word);

        // A char is a number: arithmetic and comparisons work on its code
        char c = 'a';
        System.out.println("'a' as int = " + (int) c + ", 'a' + 1 = " + (char) (c + 1));
        System.out.println("'7' - '0' = " + ('7' - '0'));
        System.out.println("getNumericValue('7') = " + Character.getNumericValue('7'));

        try {
            word.charAt(6);
        } catch (StringIndexOutOfBoundsException e) {
            System.out.println("charAt(6): " + e.getMessage());
        }
    }
}

Output:

Output
first = K, last = n
spaced out: K o t l i n
sorted letters: iklnot
original unchanged: Kotlin
'a' as int = 97, 'a' + 1 = b
'7' - '0' = 7
getNumericValue('7') = 7
charAt(6): Index 6 out of bounds for length 6
  • Valid indexes run from 0 to length() - 1, so the last character is charAt(word.length() - 1). charAt(6) on a six-letter word threw StringIndexOutOfBoundsException.
  • toCharArray() returns a new array, so sorting it changed nothing in the original string. new String(letters) turns the sorted chars back into a string, the usual way to build an anagram key.
  • A char is an unsigned 16-bit integer: 'a' is 97, and (char) ('a' + 1) is b. Without the cast, 'a' + 1 is the int 98, because arithmetic promotes char to int.
  • '7' - '0' is 7 because the ASCII digits are consecutive codes. Character.getNumericValue also handles other scripts.

Code points and surrogate pairs

The test text mixes ASCII, two BMP symbols that need one char each, and two characters outside the BMP: the G clef U+1D11E and a CJK Extension B ideograph, U+2070E, which is used in Cantonese and in names.

Java
public class CodePoints {

    public static void main(String[] args) {
        // U+2764 heavy heart and U+2615 hot beverage are in the BMP: one char each.
        // U+1D11E (G clef) and U+2070E (a rare CJK ideograph) need two chars each.
        String text = "I \u2764 Java \u2615 \uD834\uDD1E \uD841\uDF0E";

        System.out.println("length():          " + text.length());
        System.out.println("codePointCount():  " + text.codePointCount(0, text.length()));

        // chars() streams UTF-16 units; supplementary characters appear as two surrogates
        long surrogates = text.chars().filter(ch -> Character.isSurrogate((char) ch)).count();
        System.out.println("surrogate chars:   " + surrogates);
        char high = text.charAt(text.length() - 2);
        System.out.printf("charAt(length - 2) = U+%04X, high surrogate: %b%n", (int) high,
            Character.isHighSurrogate(high));

        // codePoints() streams whole characters
        text.codePoints()
            .filter(cp -> cp > 127)
            .forEach(cp -> System.out.printf("U+%04X %-3s chars=%d  %s%n",
                cp, Character.toString(cp),
                Character.charCount(cp), Character.getName(cp)));

        // Walking by code point with an index
        int i = 0;
        int count = 0;
        while (i < text.length()) {
            int cp = text.codePointAt(i);
            i += Character.charCount(cp);
            count++;
        }
        System.out.println("manual walk counted " + count + " code points");

        // Reversing by char breaks surrogate pairs; by code point it does not
        String clef = "a\uD834\uDD1Eb";
        StringBuilder byChar = new StringBuilder();
        for (int k = clef.length() - 1; k >= 0; k--) {
            byChar.append(clef.charAt(k));
        }
        System.out.println("reverse by char valid? " + isValid(byChar.toString())
            + ", StringBuilder.reverse valid? "
            + isValid(new StringBuilder(clef).reverse().toString()));
    }

    // True when every surrogate is part of a high-low pair
    static boolean isValid(String s) {
        return s.codePoints().noneMatch(cp -> cp >= 0xD800 && cp <= 0xDFFF);
    }
}

Output:

Output
length():          16
codePointCount():  14
surrogate chars:   4
charAt(length - 2) = U+D841, high surrogate: true
U+2764 ❤   chars=1  HEAVY BLACK HEART
U+2615 ☕   chars=1  HOT BEVERAGE
U+1D11E 𝄞  chars=2  MUSICAL SYMBOL G CLEF
U+2070E 𠜎  chars=2  CJK UNIFIED IDEOGRAPHS EXTENSION B 2070E
manual walk counted 14 code points
reverse by char valid? false, StringBuilder.reverse valid? true
  • length() is 16 but there are 14 code points: each of the two supplementary characters takes two chars, which chars() shows as 4 surrogates.
  • charAt near the end returned U+D841, half of the ideograph. Passing that half to Character.isLetter(char) or printing it alone gives wrong results.
  • codePoints() yields whole characters. Character.charCount(cp) says how many chars each one uses, and Character.getName gives its official Unicode name.
  • The manual loop uses codePointAt(i) and advances by charCount, the index-based equivalent of codePoints().
  • Reversing char by char swaps the two halves of the pair into an invalid order, while StringBuilder.reverse() keeps pairs together.

Use code point methods whenever text comes from users: names, chat messages and social media posts regularly contain characters outside the BMP. Cutting such text by index is covered on the substring page.

Classifying characters with Character

Character answers questions such as "is this a letter?" using the Unicode database, not just ASCII ranges. The input is a password-like string with one non-ASCII letter, followed by characters from several scripts.

Java
public class CharacterClass {

    public static void main(String[] args) {
        String input = "Pass w0rd_\u00E4!";
        int letters = 0;
        int digits = 0;
        int spaces = 0;
        int other = 0;
        int upper = 0;
        for (char ch : input.toCharArray()) {
            if (Character.isLetter(ch)) {
                letters++;
                if (Character.isUpperCase(ch)) {
                    upper++;
                }
            } else if (Character.isDigit(ch)) {
                digits++;
            } else if (Character.isWhitespace(ch)) {
                spaces++;
            } else {
                other++;
            }
        }
        System.out.printf("letters=%d (upper=%d) digits=%d spaces=%d other=%d%n",
            letters, upper, digits, spaces, other);

        // Non-ASCII letters and digits count too
        System.out.println("isLetter('\u00E4')            = " + Character.isLetter('\u00E4'));
        System.out.println("isDigit('\u0663') (Arabic 3) = " + Character.isDigit('\u0663')
            + ", digit value " + Character.digit('\u0663', 10));
        System.out.println("isLetterOrDigit('_')     = " + Character.isLetterOrDigit('_'));
        System.out.println("isJavaIdentifierStart('_') = " + Character.isJavaIdentifierStart('_')
            + ", ('$') = " + Character.isJavaIdentifierStart('$'));

        // General category, script and block
        for (int cp : new int[] {'A', '\u00E4', '\u0663', '\u20AC', '\u4E16', 0x1D11E}) {
            System.out.printf("U+%04X type=%-2d script=%-8s block=%s%n", cp, Character.getType(cp),
                Character.UnicodeScript.of(cp), Character.UnicodeBlock.of(cp));
        }
        System.out.println("UPPERCASE_LETTER=" + Character.UPPERCASE_LETTER
            + " LOWERCASE_LETTER=" + Character.LOWERCASE_LETTER
            + " DECIMAL_DIGIT_NUMBER=" + Character.DECIMAL_DIGIT_NUMBER
            + " CURRENCY_SYMBOL=" + Character.CURRENCY_SYMBOL
            + " OTHER_LETTER=" + Character.OTHER_LETTER
            + " OTHER_SYMBOL=" + Character.OTHER_SYMBOL);
    }
}

Output:

Output
letters=8 (upper=1) digits=1 spaces=1 other=2
isLetter('ä')            = true
isDigit('٣') (Arabic 3) = true, digit value 3
isLetterOrDigit('_')     = false
isJavaIdentifierStart('_') = true, ('$') = true
U+0041 type=1  script=LATIN    block=BASIC_LATIN
U+00E4 type=2  script=LATIN    block=LATIN_1_SUPPLEMENT
U+0663 type=9  script=ARABIC   block=ARABIC
U+20AC type=26 script=COMMON   block=CURRENCY_SYMBOLS
U+4E16 type=5  script=HAN      block=CJK_UNIFIED_IDEOGRAPHS
U+1D11E type=28 script=COMMON   block=MUSICAL_SYMBOLS
UPPERCASE_LETTER=1 LOWERCASE_LETTER=2 DECIMAL_DIGIT_NUMBER=9 CURRENCY_SYMBOL=26 OTHER_LETTER=5 OTHER_SYMBOL=28
  • The counts include ä as a letter: 8 letters, 1 digit (0), 1 space, and _ and ! as other.
  • isDigit is true for the Arabic-Indic digit three, and Character.digit gives its value, 3. Code that checks isDigit and then does c - '0' gets a wrong number for such input; check c >= '0' && c <= '9' when only ASCII digits are allowed.
  • _ is not a letter or digit, but it can start a Java identifier, as can $.
  • getType returns the general category as a number that matches constants such as Character.UPPERCASE_LETTER (1) and CURRENCY_SYMBOL (26). UnicodeScript names the writing system and UnicodeBlock the range of code points; the euro sign and the G clef belong to the COMMON script, shared by all writing systems.
  • Prefer the int overloads, such as isLetter(int), with code points. The char versions cannot classify supplementary characters.

Case mapping changes length and depends on locale

Upper- and lowercasing look like one-to-one character swaps, but they are not. The inputs are the German sharp s, Turkish dotted and dotless i, and a Latin digraph, the cases that break that assumption.

Java
import java.util.Locale;

public class CaseMapping {

    public static void main(String[] args) {
        // Character methods map one char to one char; String methods can change the length
        System.out.println("Character.toUpperCase('\u00DF') = " + Character.toUpperCase('\u00DF'));
        System.out.println("\"stra\u00DFe\".toUpperCase()       = "
            + "stra\u00DFe".toUpperCase(Locale.ROOT)
            + " (length 6 -> " + "stra\u00DFe".toUpperCase(Locale.ROOT).length() + ")");

        // Locale-sensitive: Turkish has dotted and dotless i
        Locale tr = Locale.forLanguageTag("tr");
        System.out.println("\"title\".toUpperCase(ROOT) = " + "title".toUpperCase(Locale.ROOT));
        System.out.println("\"title\".toUpperCase(tr)   = " + "title".toUpperCase(tr));
        System.out.println("\"TITLE\".toLowerCase(tr)   = " + "TITLE".toLowerCase(tr));

        // Title case exists for a few digraph letters
        char dz = '\u01C6';
        System.out.printf("U+01C6 %s: upper %s, title %s%n", dz, Character.toUpperCase(dz),
            Character.toTitleCase(dz));

        // Case-insensitive comparison is not the same as comparing lowercase copies
        System.out.println("equalsIgnoreCase(\"STRASSE\", \"stra\u00DFe\") = "
            + "STRASSE".equalsIgnoreCase("stra\u00DFe"));
        System.out.println("upper-case both, equals            = "
            + "STRASSE".equals("stra\u00DFe".toUpperCase(Locale.ROOT)));

        // Capitalize the first letter: substring(0, 1) is safe only for a BMP first char
        String word = "\u00E9cole";
        String cap = word.substring(0, 1).toUpperCase(Locale.ROOT) + word.substring(1);
        System.out.println("capitalized: " + cap);
    }
}

Output:

Output
Character.toUpperCase('ß') = ß
"straße".toUpperCase()       = STRASSE (length 6 -> 7)
"title".toUpperCase(ROOT) = TITLE
"title".toUpperCase(tr)   = TİTLE
"TITLE".toLowerCase(tr)   = tıtle
U+01C6 dž: upper DŽ, title Dž
equalsIgnoreCase("STRASSE", "straße") = false
upper-case both, equals            = true
capitalized: École
  • Character.toUpperCase('ß') returns ß unchanged, because a single char cannot hold the result. String.toUpperCase maps it to SS, so straße grows from 6 to 7 characters. Code that keeps indexes from before the conversion breaks.
  • In the Turkish locale, i uppercases to İ and I lowercases to dotless ı. Always pass a locale: Locale.ROOT for identifiers and keys, the user's locale for text shown to them.
  • A few letters have a separate title case: dž becomes DŽ in uppercase but Dž at the start of a word.
  • equalsIgnoreCase("STRASSE", "straße") is false, because it compares char by char. Uppercasing both strings first makes them equal. For language-aware comparison, see the string comparison page.

Accents, normalization and graphemes

The same visible text can be stored in different ways. The program writes café with a precomposed é and with e plus a combining accent, as text from macOS file names or some keyboards often is, and then counts the characters a reader sees.

Java
import java.text.BreakIterator;
import java.text.Normalizer;
import java.util.regex.Pattern;

public class Graphemes {

    public static void main(String[] args) {
        String composed = "caf\u00E9";        // e-acute as one code point U+00E9
        String decomposed = "cafe\u0301";     // e followed by COMBINING ACUTE ACCENT U+0301
        System.out.println(composed + " / " + decomposed + " look the same");
        System.out.println("lengths:   " + composed.length() + " / " + decomposed.length());
        System.out.println("equals:    " + composed.equals(decomposed));

        String nfc = Normalizer.normalize(decomposed, Normalizer.Form.NFC);
        String nfd = Normalizer.normalize(composed, Normalizer.Form.NFD);
        System.out.println("NFC of decomposed equals composed:  " + nfc.equals(composed)
            + " (length " + nfc.length() + ")");
        System.out.println("NFD of composed equals decomposed:  " + nfd.equals(decomposed)
            + " (length " + nfd.length() + ")");

        // Removing accents: decompose, then drop the combining marks
        String plain = Normalizer.normalize("cr\u00E8me br\u00FBl\u00E9e", Normalizer.Form.NFD)
            .replaceAll("\\p{M}", "");
        System.out.println("accents removed: " + plain);

        // User-perceived characters (grapheme clusters)
        String text = "ne\u0301 \uD83C\uDDE9\uD83C\uDDEA";    // "ne-acute", space, German flag
        System.out.println(text + ": " + text.length() + " chars, "
            + text.codePointCount(0, text.length()) + " code points, "
            + countBreaks(text) + " graphemes (BreakIterator), "
            + Pattern.compile("\\X").matcher(text).results().count() + " graphemes (\\X)");
    }

    static int countBreaks(String s) {
        BreakIterator it = BreakIterator.getCharacterInstance();
        it.setText(s);
        int n = 0;
        while (it.next() != BreakIterator.DONE) {
            n++;
        }
        return n;
    }
}

Output:

Output
café / café look the same
lengths:   4 / 5
equals:    false
NFC of decomposed equals composed:  true (length 4)
NFD of composed equals decomposed:  true (length 5)
accents removed: creme brulee
né 🇩🇪: 8 chars, 6 code points, 4 graphemes (BreakIterator), 4 graphemes (\X)
  • The two forms look identical but have lengths 4 and 5, and equals is false. A user who types the name one way cannot find a record stored the other way.
  • Normalizer converts between forms. NFC composes characters where possible and NFD decomposes them; after normalizing both sides to the same form, they are equal. Normalize text to NFC when it enters a system.
  • Decomposing and then removing combining marks, the regex class \p{M}, strips accents: crème brûlée became creme brulee. That is useful for search keys, though not correct for every language.
  • The last line has 8 chars and 6 code points, but a reader sees 4 characters: n, é, a space and the flag. Both BreakIterator.getCharacterInstance() and the regex \X (Java 9) count grapheme clusters.

How fast is each way of looping?

The program counts letters in a 10 million character ASCII string with each approach. There are three runs per approach, and the output shows the fastest.

Java
import java.util.Random;
import java.util.function.ToLongFunction;

public class IterateSpeed {

    public static void main(String[] args) {
        Random random = new Random(3);
        StringBuilder sb = new StringBuilder();
        while (sb.length() < 10000000) {
            sb.append((char) (' ' + random.nextInt(95)));
        }
        String s = sb.toString();
        System.out.printf("count letters in %,d chars%n", s.length());

        time("charAt loop", s, str -> {
            long n = 0;
            for (int i = 0; i < str.length(); i++) {
                if (Character.isLetter(str.charAt(i))) {
                    n++;
                }
            }
            return n;
        });
        time("toCharArray for-each", s, str -> {
            long n = 0;
            for (char c : str.toCharArray()) {
                if (Character.isLetter(c)) {
                    n++;
                }
            }
            return n;
        });
        time("chars().filter().count()", s, str -> str.chars().filter(Character::isLetter).count());
        time("codePoints().filter()",
            s, str -> str.codePoints().filter(Character::isLetter).count());
        time("codePointAt loop", s, str -> {
            long n = 0;
            for (int i = 0; i < str.length(); ) {
                int cp = str.codePointAt(i);
                if (Character.isLetter(cp)) {
                    n++;
                }
                i += Character.charCount(cp);
            }
            return n;
        });
    }

    // Best of 3 runs
    static void time(String name, String s, ToLongFunction<String> f) {
        long best = Long.MAX_VALUE;
        long result = 0;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            result = f.applyAsLong(s);
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("%-26s %6.1f ms  %,d letters%n", name, best / 1e6, result);
    }
}

Output (JDK 21 on a 2-CPU Linux machine, rough comparison only):

Output
count letters in 10,000,000 chars
charAt loop                  12.2 ms  5,475,431 letters
toCharArray for-each         19.2 ms  5,475,431 letters
chars().filter().count()     47.9 ms  5,475,431 letters
codePoints().filter()        45.1 ms  5,475,431 letters
codePointAt loop              5.3 ms  5,475,431 letters
  • The index loops with charAt or codePointAt were the fastest. The JIT compiles them into a tight loop over the string's internal byte array, and handling code points cost nothing measurable on ASCII text.
  • toCharArray was slower because it first copies 10 million chars, 20 MB, into a new array.
  • The chars() and codePoints() streams were about four times slower than the charAt loop, and further behind the codePointAt loop. That is fine for most code, but noticeable in a parser.

Which approach to use

Choosing how to work with characters
TaskUse
One character at a positions.charAt(i)
Loop over ASCII or BMP-only textfor (int i = 0; i < s.length(); i++) with charAt
Loop over any user textcodePointAt with Character.charCount, or codePoints()
Sort or edit the characterstoCharArray(), then new String(array)
Count what users seeBreakIterator.getCharacterInstance() or \X
Classify a characterCharacter.isLetter(int), isDigit(int), getType(int)
Only ASCII digits allowedc >= '0' && c <= '9'
Change casetoUpperCase(Locale) on the whole string, not per char
Compare text from different sourcesNormalizer.normalize(s, Form.NFC) first

How text becomes bytes is covered on the charsets page.