Java StringBuilder.setCharAt() – Examples

In this tutorial, we will learn about the Java StringBuilder.setCharAt() function, and learn how to use this function to set character at specific index, with the help of examples.

setCharAt(int index, char ch)

StringBuilder.setCharAt() The character at the specified index is set to ch.

ADVERTISEMENT

Syntax

The syntax of setCharAt() function is

setCharAt(int index, char ch)

where

ParameterDescription
indexThe index in StringBuilder sequence to modify.
chThe new character we set at the index in StringBuilder sequence.

Returns

The function returns void, meaning it returns nothing.

Example 1 – setCharAt(index, ch)

In this example, we will take a StringBuilder sequence "abcdef" and set the char at index 2 with char E. We will set the character using setCharAt() method.

Java Program

public class Example { 
    public static void main(String[] args) { 
        StringBuilder stringBuilder = new StringBuilder("abcdef");
        System.out.println("Before setting char : " + stringBuilder.toString());
        
        char ch = 'E';
        int index = 2;
        stringBuilder.setCharAt(index, ch);  
        System.out.println("After  setting char : " + stringBuilder.toString()); 
    }
}

Output

Before setting char : abcdef
After  setting char : abEdef

Example 2 – setCharAt(index, ch) – index out of bounds

In this example, we will take an index that is out of bounds for the StringBuilder sequence. setCharAt() should throw java.lang.StringIndexOutOfBoundsException.

Java Program

public class Example { 
    public static void main(String[] args) { 
        StringBuilder stringBuilder = new StringBuilder("abcdef");
        System.out.println("Before setting char : " + stringBuilder.toString());
        
        char ch = 'E';
        int index = 9;
        stringBuilder.setCharAt(index, ch);  
        System.out.println("After  setting char : " + stringBuilder.toString()); 
    }
}

Output

Before setting char : abcdef
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 9,length 6
	at java.base/java.lang.String.checkIndex(Unknown Source)
	at java.base/java.lang.AbstractStringBuilder.setCharAt(Unknown Source)
	at java.base/java.lang.StringBuilder.setCharAt(Unknown Source)
	at Example.main(Example.java:8)

Conclusion

In this Java Tutorial, we have learnt the syntax of Java StringBuilder.setCharAt() function, and also learnt how to use this function with the help of examples.