.charAt()

christian.dinh2481 total contributions
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
All contributors
- christian.dinh2481 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions
- robgmerrill124 total contributions
- christian.dinh
- Anonymous contributor
- robgmerrill
Looking to contribute?
- 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.