Topics Index

Strings > StringBuffer >
Siva Nookala - 06 Oct 2016
The charAt() method is used to get a character at the specified index in the sequence. The index range is [0, length of the sequence - 1].

Syntax of charAt() method:
public char charAt(int index)
The setCharAt() method is used to set a character at the specified index. The sequence is identical except that it sets the specified character at the specified index.

Syntax of setCharAt() method:
public void setCharAt(int index, char ch)
Note that setCharAt method alter the characters in the sequence, it does not append characters to the sequence.

Here is an example program implementing these methods:
StringBuffer charAt and setCharAt
class CharAtAndSetCharAtDemo
    public static void main(String arg[])
        StringBuffer sb = new StringBuffer("'Happy New Year!'");
        for (int i = 0; i < sb.length(); i++)
            System.out.print(sb.charAt(i)); // LINE A
        sb.setCharAt(sb.length() - 1, '"'); // LINE B
        sb.setCharAt(0, '"'); // LINE C

'Happy New Year!'
"Happy New Year!"


Each character in the sequence is obtained using charAt() method and then printed at LINE A.
At LINE B and LINE C the character at positions 'sb.length() - 1' & 0 are changed from single quotes(') to double quotes (") using set method.

  • Give index values that are out of the range [0, sequence length - 1]. For e.g., try setCharAt(-2, 'A') or setCharAt(15, 'A')
  • Try for the below code.
    StringBuffer sb = new StringBuffer("merit Campus");
    sb.setCharAt(0, 'M');
    The output for the above code will be Merit Campus, since the setChartAt replaced the character m with M.

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App