setCharAt() StringBuffer Example

setCharAt() StringBuffer Example

To manipulate string, java.lang.StringBuffer class comes with many methods, otherwise, which will take long laborious coding as in C/C++. One such method is setCharAt(int, char) that replaces a single character in the string buffer. Now read setCharAt() StringBuffer.

What Java API says of setCharAt() StringBuffer:

  • public synchronized void setCharAt(int index1, char1): Replaces the character in the StringBuffer at index number index1 with character char1.
Following setCharAt() StringBuffer example illustrates.

setCharAt() StringBuffer
Output screenshot on setCharAt() StringBuffer Example

sb1.setCharAt(0, 'a');
sb1.setCharAt(4, 'e');
sb1.setCharAt(10, 'y');

setCharAt(0, 'a') replaces A (at 0 index number) with a and setCharAt(4, 'e') replaces E (at 4 index number) with e. We have seen earlier how to replace a group of characters.

setCharAt(10, 'y') throws StringIndexOutOfBoundsException as 10th index number does not exist in sb1.

A similar example exists replacing a group of characters "replace() StringBuffer Example".

Leave a Reply

Your email address will not be published. Required fields are marked *