Java StringBuilder setCharAt() method sets a specified character at the given index. This method changes the character sequence represented by StringBuilder 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 StringBuilder 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 StringBuilder 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: Sets a new character in the existing sequence
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hi Text"); System.out.println("Old Sequence: "+sb); //set char 'N' at the index 3 sb.setCharAt(3, 'N'); System.out.println("New Sequence: "+sb); } }
Output:
Example 2: Changes the first and last character of Sequence
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("X to Y"); System.out.println("Old Sequence: "+sb); //set first char as 'A' sb.setCharAt(0, 'A'); //set last char as 'Z' sb.setCharAt(sb.length()-1, 'Z'); System.out.println("New Sequence: "+sb); } }
Output:
Example 3: Specified index is equal to the length of Sequence
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Hi"); System.out.println("Old Sequence: "+sb); //if index is >= sb.length() //last char is at index 1 //index 2 is out of sequence range sb.setCharAt(2, 'A'); System.out.println("New Sequence: "+sb); } }
Output: