java.lang.StringBuilder setCharAt(int index,char ch)
Description
Notes:
- An IndexOutOfBoundsException will be thrown by the setCharAt() method if the index is negative or greater than or equal to length().
Method Syntax
public void setCharAt(int index,char ch)
Method Argument
| Data Type | Parameter | Description |
|---|---|---|
| int | index | index of the char to be set. |
| char | ch | the new character. |
Method Returns
The setCharAt(int index,char ch) method returns void.
Compatibility
Requires Java 1.5 and up
Java StringBuilder setCharAt(int index,char ch) Example
Below is a java code demonstrates the use of setCharAt() method of StringBuilder class. The example presented might be simple however it shows the behavior of the setCharAt() method.
package com.javatutorialhq.java.examples;
/*
* A java example source code to demonstrate
* the use of setCharAt() method of StringBuilder class
*/
public class StringBuilderSetCharAtExample {
public static void main(String[] args) {
// initialize the StringBuilder object
StringBuilder sb = new StringBuilder("javatutorialhq.com");
System.out.println("Contents of StringBuilder:" + sb);
int index = 15;
char ch = 'X';
// change the character at index 15
sb.setCharAt(index, ch);
System.out.println("New Contents of StringBuilder:" + sb);
}
}
The java example source code above, demonstrates the use of setCharAt(int index,char ch) method of StringBuilder class. Initially the code assigns a string “javatutorialhq.com” as initial contents of the string buffer. Then we use setCharAt(int index,char ch) method to replace the character at index 15 with character ‘X’.
