Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.charAt()

Returns the character at the given index.

Available since: Java 1.0

Syntax

public char charAt(int index)

Parameters

ParameterTypeDescription
indexintThe position of the character, counting from zero. Must be from 0 to length() - 1.

Return value

charThe character as a char value.

Examples

The first and the last character:

void main() {
    String name = "Anna";
    IO.println(name.charAt(0));
    IO.println(name.charAt(name.length() - 1));
}

Output:

A
a

Looping over the characters:

void main() {
    String word = "code";
    for (int i = 0; i < word.length(); i++) {
        IO.print(word.charAt(i) + " ");
    }
    IO.println();
}

Output:

c o d e 

An index outside the string throws an exception:

void main() {
    try {
        "abc".charAt(3);
    } catch (StringIndexOutOfBoundsException e) {
        IO.println(e.getMessage());
    }
}

Output:

Index 3 out of bounds for length 3

Notes

A char is a number, so 'a' + 1 gives 98, not "b". To join characters into a string, start the expression with a string: "" + c1 + c2.

See also

Related recipes

In the tutorial

  • Strings — The String type in Java: creating strings, joining with +, length, characters by index, escaping and comparing with equals.

Thanks for reading!

Donate to the site — we work hard for you.