Java StringBuffer setCharAt() method sets a specified character at the given index. This method changes the character sequence represented by StringBuffer object, as it replaces the existing char with new char. In this tutorial, we will discuss setCharAt() method with examples.
Syntax of setCharAt() method
sb.setCharAt(2, 'A'); //changes the char at index 2 with char 'A'
Here, sb
is an object of StringBuffer
class.
setCharAt() Description
public void setCharAt(int index, char ch): Sets the specified char ch
at the given index
in this char sequence. The length of the StringBuffer object remains unchanged.
setCharAt() Parameters
This method takes two parameters:
- int index: Specifies the position of a character in the sequence that needs to be replaced with new char.
- char ch: Represents a char that replaces the character at given index.
setCharAt() Return Value
- It does not return anything.
- It throws
IndexOutOfBoundsException
, if specifiedindex < 0
or>= sb.length()
.
Example 1: Set a new char in the given sequence
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Nice Book"); System.out.println("Old Sequence: "+sb); //set char 'H' at the index 5 sb.setCharAt(5, 'H'); System.out.println("New Sequence: "+sb); } }
Output:
Example 2: Change first and last character
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Book"); System.out.println("Old Sequence: "+sb); //set first char as 'C' sb.setCharAt(0, 'C'); //set last char as 'l' sb.setCharAt(sb.length()-1, 'l'); System.out.println("New Sequence: "+sb); } }
Output:
Example 3: Specified index is out of range
public class JavaExample { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Book"); System.out.println("Old Sequence: "+sb); //if index is >= sb.length() //last char is at index 3 //index 4 is out of sequence range sb.setCharAt(4, 'L'); System.out.println("New Sequence: "+sb); } }
Output: