charAt(): This method is available in java.lang.AbstractStringBuilder class of Java.
Syntax:
char java.lang.AbstractStringBuilder.charAt(int index)
This method takes one argument of type int as a parameter. This method returns the char value in this sequence at the specified index.
Note: The index argument must be greater than or equal to 0, and less than the length of this sequence.
Parameters: One parameter is required for this method.
index: the index of the desired char value.
Returns: the char value at the specified index.
Throws:
StringIndexOutOfBoundsException - if index is negative or greater than or equal to length().
For Example:
StringBuilder str = new StringBuilder("Hello 123")
int index = 15
str.charAt(index) = > It returns l.
Approach 1: When the index is in the range.
Java
public class CharAt {public static void main(String[] args) {StringBuilder str = new StringBuilder("Hello 123");int index = 2;System.out.println(str.charAt(index));}}
Output:
l
Approach 2: When the index is out of range.
Java
public class CharAt {public static void main(String[] args) {StringBuilder str = new StringBuilder("Hello 123");int index = 15;System.out.println(str.charAt(index));}}
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 15, length 9 at java.base/java.lang.String.checkIndex(String.java:3693) at java.base/java.lang.AbstractStringBuilder.charAt(AbstractStringBuilder.java:351) at java.base/java.lang.StringBuilder.charAt(StringBuilder.java:85)
No comments:
Post a Comment