.charAt()
Published Jul 23, 2021Updated Sep 3, 2021
Contribute to Docs
Returns the character at the given index in the string.
Syntax
string.charAt(int index)
index
(required): An integer value that represents the index of the character value you want to retrieve.
Example 1
Use .charAt()
to print the first five characters of the string "Hello World"
:
class CharacterAt {public static void main(String[] args) {String greeting = "Hello World";System.out.println(greeting.charAt(0));System.out.println(greeting.charAt(1));System.out.println(greeting.charAt(2));System.out.println(greeting.charAt(3));System.out.println(greeting.charAt(4));}}
The output would be:
H
e
l
l
o
Example 2
Use .charAt()
in a for loop to print all the characters in the string "Hello World"
:
class PrintAllCharacters {public static void main(String[] args) {String greeting = "Hello World";for (int i = 0; i < greeting.length(); i++) {char ch = greeting.charAt(i);System.out.println(ch);}}}
The output would be:
H
e
l
l
o
W
o
r
l
d
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours