Java String charAt()
The Java String class charAt() method returns a char value at the given index number.
The index number starts from 0 and goes to n-1, where n is the length of the string. It returns StringIndexOutOfBoundsException, if the given index number is greater than or equal to this string length or a negative number.
Syntax
The method accepts index as a parameter. The starting index is 0. It returns a character at a specific index position in a string. It throws StringIndexOutOfBoundsException if the index is a negative value or greater than this string length.
Specified by
CharSequence interface, located inside java.lang package.
Internal implementation
Java String charAt() Method Examples
Let’s see Java program related to string in which we will use charAt() method that perform some operation on the give string.
FileName: CharAtExample.java
Output:
t
Let’s see the example of the charAt() method where we are passing a greater index value. In such a case, it throws StringIndexOutOfBoundsException at run time.
FileName: CharAtExample.java
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10 at java.lang.String.charAt(String.java:658) at CharAtExample.main(CharAtExample.java:4)
Accessing First and Last Character by Using the charAt() Method
Let’s see a simple example where we are accessing first and last character from the provided string.
FileName: CharAtExample3.java
Output:
Character at 0 index is: W Character at last index is: l
Print Characters Presented at Odd Positions by Using the charAt() Method
Let’s see an example where we are accessing all the elements present at odd index.
FileName: CharAtExample4.java
Output:
Char at 1 place e Char at 3 place c Char at 5 place m Char at 7 place Char at 9 place o Char at 11 place J Char at 13 place v Char at 15 place t Char at 17 place o Char at 19 place n Char at 21 place Char at 23 place o Char at 25 place t Char at 27 place l
The position such as 7 and 21 denotes the space.
Counting Frequency of a character in a String by Using the charAt() Method
Let’s see an example in which we are counting frequency of a character in the given string.
FileName: CharAtExample5.java
Output:
Frequency of t is: 4
Counting the Number of Vowels in a String by Using the chatAt() Method
Let’s see an example where we are counting the number of vowels present in a string with the help of the charAt() method.
FileName: CharAtExample6.java
Output:
String: TutorAspire is a great site for learning Java. Total number of vowels in the string are: 16 String: One apple in a day keeps doctor away. Total number of vowels in the string are: 13