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
Syntax
string.charAt(index)
Parameters
| Parameter | Description |
|---|---|
indexint |
Position from 0 to length() - 1. |
Return value
A char.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
string.length()· Return the number of characters (UTF-16 code units) in a string. An empty string has length 0.string.substring()· Return part of a string from a start index up to (not including) an end index. The original is unchanged.- Java Strings · tutorial