Java Reference ยท java.lang
Java String.charAt() method
Reference for Java String.charAt(): get the char at an index, the StringIndexOutOfBoundsException rule, looping over characters and surrogate pairs.
String.charAt(int index) returns the char at the given zero-based position. It is the basic way to examine a string one character at a time, for example to check digits, count letters or reverse text.
The index must satisfy 0 <= index < length(). Anything else throws StringIndexOutOfBoundsException. The method returns a UTF-16 code unit, so characters outside the Basic Multilingual Plane (many emoji) are split across two indexes.
char first = "Java".charAt(0); // 'J'
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public char charAt(int index)
| Name | Description |
|---|---|
index |
Zero-based position, from 0 to length() - 1. |
Returns: the char at that position.
Throws: StringIndexOutOfBoundsException (a subclass of IndexOutOfBoundsException) if the index is negative or not less than length(). NullPointerException if the string reference is null.
Usage notes
- Zero-based. The last character is at
length() - 1; there is no negative indexing like in Python. charis an integer type.c + 1is anint; cast back with(char).charvalues can be compared and used inswitch.- Surrogate pairs. For text with emoji, use
codePointAt(i)and advance byCharacter.charCount(cp), or iterate withs.codePoints(). - Prefer for-each over a
char[]when you simply need to visit every character:for (char c : s.toCharArray())(see toCharArray()). It copies the string once but reads cleanly. - Character tests:
Character.isDigit,isLetter,isWhitespace,isUpperCaseand friends take achar(or anintcode point). - Comparing:
s.charAt(0) == 'J'compares primitives, so==is correct here. For a string prefix check use startsWith(). - Empty string.
"".charAt(0)always throws, so checkisEmpty()first. - Performance. O(1) with bounds checking.