StringBuffer charAt() in Java

charAt(): This method is available in java.lang.StringBuffer class of Java.

Syntax:

char java.lang.StringBuffer.charAt(int index)

This method takes one argument of type int as its parameter. This method returns the char value at the specified index. An index ranges from zero to length() - 1. The first char value of the sequence is at index zero, the next at index one, and so on, as for array indexing.

Parameters: One parameter is required for this method.

index: the index of the char value to be returned.

Returns: the specified char value.

Throws:

IndexOutOfBoundsException - if the index argument is negative or not less than length().

For Example:

StringBuffer str = new StringBuffer("Hello 123")

int index = 2

str.charAt(index) = > It returns l.

Approach 1 : When index is within in the length of the String.

Java

public class CharAt {
    public static void main(String[] args) {

        StringBuffer str = new StringBuffer("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) {

        StringBuffer str = new StringBuffer("Hello 123");

        int index = 14;
        System.out.println(str.charAt(index));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 14, 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.StringBuffer.charAt(StringBuffer.java:237)


No comments:

Post a Comment