Skip to content
Tutorials Center
My learning

Topics

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.

Java
char first = "Java".charAt(0);   // 'J'

Try it

Java Reading characters by index

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.

Java Counting character kinds

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

Java
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.
  • char is an integer type. c + 1 is an int; cast back with (char). char values can be compared and used in switch.
  • Surrogate pairs. For text with emoji, use codePointAt(i) and advance by Character.charCount(cp), or iterate with s.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, isUpperCase and friends take a char (or an int code 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 check isEmpty() first.
  • Performance. O(1) with bounds checking.