StringBuffer charAt() Method in Java: Usage and Examples

Rumman Ansari   Software Engineer   2024-07-05 03:39:41   6302  Share
Subject Syllabus DetailsSubject Details 1 Program
☰ TContent
☰Fullscreen

Table of Content:

The value of a single character can be obtained from a StringBuffer via the charAt( ) method.

Syntax

char charAt(int where)

Parameters

For charAt( ), where specifies the index of the character being obtained.

Specified by

charAt in interface CharSequence

Returns

Returns the character present at the specified index number in the string buffer.

Throws

IndexOutOfBoundsException - if index is negative or greater than or equal to length().

Discussion

The value of a single character can be obtained from a StringBuffer via the charAt( ) method.

Returns the char value in this sequence at the specified index. The first char value is at index 0, the next at index 1, and so on, as in array indexing.

The index argument must be greater than or equal to 0, and less than the length of this sequence.

If the char value specified by the index is a surrogate, the surrogate value is returned.

Program

public class DemocharAt
{
  public static void main(String args[])
  {
    StringBuffer sb1 = new StringBuffer("ATNYLA");
    char ch = sb1.charAt(2);                    // index number starts from 0
    System.out.println("Character present at index number 2: " + ch);  // C

    System.out.println("Character present at index number 10: " + sb1.charAt(10));
  }
}

Output

Character present at index number 2: N
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10
        at java.lang.StringBuffer.charAt(StringBuffer.java:202)
        at DemocharAt.main(DemocharAt.java:9)
Press any key to continue . . .