StringBuilder charAt() in Java with Examples (original) (raw)

Last Updated : 15 Oct, 2018

The charAt(int index) method of StringBuilder Class is used to return the character at the specified index of String contained by StringBuilder Object. The index value should lie between 0 and length()-1.

Syntax:

public char charAt(int index)

Parameters: This method accepts one int type parameter index which represents index of the character to be returned.

Return Value: This method returns character at the specified position.

Exception: This method throws IndexOutOfBoundsException when index is negative or greater than or equal to length().

Below programs demonstrate the charAt() method of StringBuilder Class:

Example 1:

class GFG {

`` public static void main(String[] args)

`` {

`` StringBuilder str = new StringBuilder();

`` str.append( "Geek" );

`` char ch = str.charAt( 1 );

`` System.out.println( "StringBuilder Object"

`` + " contains = " + str);

`` System.out.println( "Character at Position 1"

`` + " in StringBuilder = " + ch);

`` }

}

Output:

StringBuilder Object contains = Geek Character at Position 1 in StringBuilder = e

Example 2:

class GFG {

`` public static void main(String[] args)

`` {

`` StringBuilder

`` str

`` = new StringBuilder( "WelcomeGeeks" );

`` System.out.println( "String is "

`` + str.toString());

`` for ( int i = 0 ; i < str.length(); i++) {

`` char ch = str.charAt(i);

`` System.out.println( "Char at position "

`` + i + " is " + ch);

`` }

`` }

}

Output:

String is WelcomeGeeks Char at position 0 is W Char at position 1 is e Char at position 2 is l Char at position 3 is c Char at position 4 is o Char at position 5 is m Char at position 6 is e Char at position 7 is G Char at position 8 is e Char at position 9 is e Char at position 10 is k Char at position 11 is s

Example 3: To demonstrate IndexOutOfBoundException

class GFG {

`` public static void main(String[] args)

`` {

`` try {

`` StringBuilder

`` str

`` = new StringBuilder( "WelcomeGeeks" );

`` char ch = str.charAt(str.length());

`` System.out.println( "Char at position "

`` + str.length() + " is "

`` + ch);

`` }

`` catch (Exception e) {

`` System.out.println( "Exception: " + e);

`` }

`` }

}

Output:

Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 12

Reference:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#charAt(int)