Topics Index

StringBuffer charAt and setCharAt - Java Example Program

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.

© meritcampus 2019

All Rights Reserved.

Open In App