Java String charAt()The java string 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 length of the string. It returns StringIndexOutOfBoundsException if given index number is greater than or equal to this string length or a negative number. Internal implementationSignatureThe signature of string charAt() method is given below: Parameterindex : index number, starts with 0 ReturnsA char value Specified byCharSequence interface, located inside java.lang package. ThrowsStringIndexOutOfBoundsException : if index is negative value or greater than this string length. Java String charAt() method exampleOutput: t StringIndexOutOfBoundsException with charAt()Let's see the example of charAt() method where we are passing greater index value. In such case, it throws StringIndexOutOfBoundsException at run time. 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) Java String charAt() Example 3Let's see a simple example where we are accessing first and last character from the provided string. Output: Character at 0 index is: W Character at last index is: l Java String charAt() Example 4Let's see an example where we are accessing all the elements present at odd index. 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 Java String charAt() Example 5Let's see an example where we are counting frequency of a character in the string. Output: Frequency of t is: 4 Next TopicJava String compareTo
|