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
- A
is a 16-bit UTF-16 code unit, an unsigned number from 0 to 65,535.char ,length() and every index in thecharAt API count chars.String - 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.
| API | Since | Works with | Best for |
|---|---|---|---|
charAt(i)length() | Java 1.0 | chars | Index loops, ASCII and BMP text |
toCharArray()getChars | Java 1.0 | A copy of the chars | Sorting or editing characters |
chars() | Java 8 | IntStream | Stream pipelines over BMP text |
codePoints() | Java 8 | IntStream | Stream pipelines over any text |
codePointAtcodePointCountoffsetByCodePoints | Java 5 | Code points | Index loops over any text |
Character.isLetter(int) | Java 5 (int overloads) | Code points | Classifying characters |
Character.toString(int)getName | Java 11, Java 7 | Code points | Printing and debugging |
BreakIterator\X | Java 1.1, Java 9 | Grapheme clusters | Counting 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, charAttoCharArraychar
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:
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
, so the last character islength() - 1 .charAt(word.length() - 1) on a six-letter word threwcharAt(6) .StringIndexOutOfBoundsException returns a new array, so sorting it changed nothing in the original string.toCharArray() turns the sorted chars back into a string, the usual way to build an anagram key.new String(letters)- A
is an unsigned 16-bit integer:char is 97, and'a' is(char) ('a' + 1) . Without the cast,b is the'a' + 1 98, because arithmetic promotesint tochar .int is 7 because the ASCII digits are consecutive codes.'7' - '0' also handles other scripts.Character.getNumericValue
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.
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:
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
is 16 but there are 14 code points: each of the two supplementary characters takes two chars, whichlength() shows as 4 surrogates.chars() near the end returned U+D841, half of the ideograph. Passing that half tocharAt or printing it alone gives wrong results.Character.isLetter(char) yields whole characters.codePoints() says how many chars each one uses, andCharacter.charCount(cp) gives its official Unicode name.Character.getName- The manual loop uses
and advances bycodePointAt(i) , the index-based equivalent ofcharCount .codePoints() - Reversing char by char swaps the two halves of the pair into an invalid order, while
keeps pairs together.StringBuilder.reverse()
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
Classifying characters with Character
Character
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:
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 (ä ), 1 space, and0 and_ as other.! is true for the Arabic-Indic digit three, andisDigit gives its value, 3. Code that checksCharacter.digit and then doesisDigit gets a wrong number for such input; checkc - '0' when only ASCII digits are allowed.c >= '0' && c <= '9' is not a letter or digit, but it can start a Java identifier, as can_ .$ returns the general category as a number that matches constants such asgetType (1) andCharacter.UPPERCASE_LETTER (26).CURRENCY_SYMBOL names the writing system andUnicodeScript the range of code points; the euro sign and the G clef belong to the COMMON script, shared by all writing systems.UnicodeBlock- Prefer the
overloads, such asint , with code points. TheisLetter(int) versions cannot classify supplementary characters.char
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.
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:
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
returnsCharacter.toUpperCase('ß') unchanged, because a singleß cannot hold the result.char maps it toString.toUpperCase , soSS grows from 6 to 7 characters. Code that keeps indexes from before the conversion breaks.straße- In the Turkish locale,
uppercases toi andİ lowercases to dotlessI . Always pass a locale:ı for identifiers and keys, the user's locale for text shown to them.Locale.ROOT - A few letters have a separate title case:
becomesdž in uppercase butDŽ at the start of a word.Dž is false, because it compares char by char. Uppercasing both strings first makes them equal. For language-aware comparison, see theequalsIgnoreCase("STRASSE", "straße")string comparison page .
Accents, normalization and graphemes
The same visible text can be stored in different ways. The program writes caféée
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:
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
is false. A user who types the name one way cannot find a record stored the other way.equals 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.Normalizer- Decomposing and then removing combining marks, the regex class
, strips accents:\p{M} becamecrème brûlée . That is useful for search keys, though not correct for every language.creme brulee - The last line has 8 chars and 6 code points, but a reader sees 4 characters:
,n , a space and the flag. Bothé and the regexBreakIterator.getCharacterInstance() (Java 9) count grapheme clusters.\X
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.
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):
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
orcharAt 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.codePointAt was slower because it first copies 10 million chars, 20 MB, into a new array.toCharArray- The
andchars() streams were about four times slower than thecodePoints() loop, and further behind thecharAt loop. That is fine for most code, but noticeable in a parser.codePointAt
Which approach to use
| Task | Use |
|---|---|
| One character at a position | s.charAt(i) |
| Loop over ASCII or BMP-only text | for (int i = 0; i < s.length(); i++)charAt |
| Loop over any user text | codePointAtCharacter.charCountcodePoints() |
| Sort or edit the characters | toCharArray()new String(array) |
| Count what users see | BreakIterator.getCharacterInstance()\X |
| Classify a character | Character.isLetter(int)isDigit(int)getType(int) |
| Only ASCII digits allowed | c >= '0' && c <= '9' |
| Change case | toUpperCase(Locale) |
| Compare text from different sources | Normalizer.normalize(s, Form.NFC) |
How text becomes bytes is covered on the