The Java String charAt() Method
This is one of the articles from our Java Tutorial for Beginners.
The Java String charAt() Method
charAt(int index) - It returns you the character that corresponds to a specific index number. Keep in mind that index numbers start from zero.
Syntax:
1 |
public char chartAt (int index) |
It will make more sense in an example.
Example
1 2 3 4 5 6 7 8 9 10 11 12 |
class Test { public static void main(String[] args) { String sentence = "I love Java"; char ch1 = sentence.charAt(0); char ch2 = sentence.charAt(5); char ch3 = sentence.charAt(9); System.out.println("The character with index number 0 is: " + ch1); System.out.println("The character with index number 5 is: " + ch2); System.out.println("The character with index number 9 is: " + ch3); } } |
If you run this code on your computer, you'll see the following in the console:
The character with index number 0 is: I
The character with index number 5 is: e
The character with index number 9 is: v
Commentary:
1 |
char ch1 = sentence.charAt(0); |
We assigned the value of index number 0 to the char variable. The character with index number 0 in the variable "sentence" is "I."
1 |
char ch2 = sentence.charAt(5); |
We assigned the value of index number 5 to the char variable. The character with index number 5 in the variable "sentence" is "e."
1 |
char ch3 = sentence.charAt(9); |
We assigned the value of index number 9 to the char variable. The character with index number 9 in the variable "sentence" is "v."
You can find more articles in our Java Tutorial for Beginners.