Home » Java programming language

Java StringBuilder setCharAt() method with example

StringBuilder Class setCharAt() method: Here, we are going to learn about the setCharAt() method of StringBuilder Class with its syntax and example.
Submitted by Preeti Jain, on December 22, 2019

StringBuilder Class setCharAt() method

  • setCharAt() method is available in java.lang package.
  • setCharAt() method is used to sets the given character at the given position and pos argument must be equal to or greater than 0 and less than the length.
  • setCharAt() method is a non-static method, it is accessible with class object only and if we try to access the method with class name then we will get an error.
  • setCharAt() method may throw an exception at the time of set character at the given position.
    IndexOutOfBoundsException – This exception may throw when the given argument pos <0 or pos > length().

Syntax:

    public void setCharAt(int pos, char c);

Parameter(s):

  • int pos – represents the position where we want to set the given character.
  • char c – represents the new character which we want to place.

Return value:

The return type of this method is void, it returns nothing.

Example:

// Java program to demonstrate the example 
// of void setCharAt(int pos, char c)
// method of StringBuilder 

public class setCharAt {
    public static void main(String[] args) {
        // Creating an StringBuilder object
        StringBuilder st_b = new StringBuilder("Java World ");

        // Display st_b 
        System.out.println("st_b = " + st_b);

        // By using setCharAt(4,'@') method is to replace the character('')
        // at index 4 in st_b with the given character('@')
        st_b.setCharAt(4, '@');

        // Display st_b
        System.out.println("st_b.setCharAt(4,'@') = " + st_b);
    }
}

Output

st_b = Java World 
st_b.setCharAt(4,'@') = Java@World 



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.