Menu
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
        }
        System.out.println();
        sb.setCharAt(sb.length() - 1, '"'); // LINE B
        sb.setCharAt(0, '"'); // LINE C
        System.out.println(sb);    
    }
}
OUTPUT

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

DESCRIPTION

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.

THINGS TO TRY
  • 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');
    System.out.println(sb);
    The output for the above code will be Merit Campus, since the setChartAt replaced the character m with M.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.