Java 25 (LTS) reference · String Methods

Java String charAt() Method

Return the character at an index (0-based). Throws StringIndexOutOfBoundsException for an invalid index.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.charAt(index)

Parameters

ParameterDescription
index
int
Position from 0 to length() - 1.

Return value

A char.

Examples

First and last character
public class Main {
    public static void main(String[] args) {
        String word = "Java";
        System.out.println(word.charAt(0));
        System.out.println(word.charAt(word.length() - 1));
    }
}

Output

J
a

Run this on your computer — see “Get Started” for setup.

Loop over characters
public class Main {
    public static void main(String[] args) {
        String s = "hello";
        int vowels = 0;
        for (int i = 0; i < s.length(); i++) {
            if ("aeiou".indexOf(s.charAt(i)) >= 0) vowels++;
        }
        System.out.println(vowels + " vowels");
    }
}

Output

2 vowels

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?