Tuesday, October 7, 2025
HomeLanguagesJavaStringBuffer setCharAt() method in Java with Examples

StringBuffer setCharAt() method in Java with Examples

The setCharAt() method of StringBuffer class sets the character at the position index to character which is the value passed as parameter to method. This method returns a new sequence which is identical to old sequence only difference is a new character ch is present at position index in new sequence. The index argument must be greater than or equal to 0, and less than the length of the String contained by StringBuffer object.

Syntax:

public void setCharAt(int index, char ch)

Parameters: This method takes two parameters:

  • index: Integer type value which refers to the index of character to be set.
  • ch: Character type value which refers to the new char.

Returns: This method returns nothing.

Exception: This method throws IndexOutOfBoundException if the index is negative or greater than length().

Below programs demonstrate the setCharAt() method of StringBuffer Class

Example 1:




// Java program to demonstrate
// the setCharAt() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuffer object
        // with a String pass as parameter
        StringBuffer str
            = new StringBuffer("Geeks For Geeks");
  
        // print string
        System.out.println("String = "
                           + str.toString());
  
        // set char at index 4 to '0'
        str.setCharAt(7, '0');
  
        // print string
        System.out.println("After setCharAt() String = "
                           + str.toString());
    }
}


Output:

String = Geeks For Geeks
After setCharAt() String = Geeks F0r Geeks

Example 2: To demonstrate IndexOutOfBoundsException.




// Java program to demonstrate
// Exception thrown by the setCharAt() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuffer object
        // with a String pass as parameter
        StringBuffer str
            = new StringBuffer("Geeks for Geeks");
  
        try {
  
            // pass index -1
            str.setCharAt(-1, 'T');
        }
  
        catch (Exception e) {
            System.out.println("Exception:" + e);
        }
    }
}


Output:

Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1

References:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#setCharAt(int, char)

RELATED ARTICLES

Most Popular

Dominic
32340 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6709 POSTS0 COMMENTS
Nicole Veronica
11872 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6829 POSTS0 COMMENTS
Ted Musemwa
7090 POSTS0 COMMENTS
Thapelo Manthata
6780 POSTS0 COMMENTS
Umr Jansen
6784 POSTS0 COMMENTS