StringBuilder setCharAt() in Java with Examples
The setCharAt(int index, char ch) method of StringBuilder class is used to set the character at the position index passed as ch. This method changes the old sequence to represents a new sequence which is identical to old sequence only difference is a new character ch is present at position index. The index argument must be greater than or equal to 0, and less than the length of the String contained by StringBUilder object.
Syntax:
public void setCharAt(int index, char ch)
Parameters:
This method accepts two parameters:
-
index – Integer type value which refers to the index of character you want to set.
-
ch – Character type value which refers to the new char.
Returns:
This method returns nothing.
Exception:
If the index is negative, greater than length() then IndexOutOfBoundsException.
Below programs illustrate the java.lang.StringBuilder.setCharAt() method:
Example 1:
class GFG {
public static void main(String[] args)
{
StringBuilder str
= new StringBuilder( "WelcomeGeeks" );
System.out.println( "String = "
+ str.toString());
str.setCharAt( 2 , 'L' );
System.out.println( "After setCharAt() String = "
+ str.toString());
}
}
|
Output:
String = WelcomeGeeks
After setCharAt() String = WeLcomeGeeks
Example 2:
class GFG {
public static void main(String[] args)
{
StringBuilder str
= new StringBuilder( "Tony Stark will die" );
System.out.println( "String = "
+ str.toString());
str.setCharAt( 9 , '1' );
System.out.println( "After setCharAt() String = "
+ str.toString());
}
}
|
Output:
String = Tony Stark will die
After setCharAt() String = Tony Star1 will die
Example 3: When negative index is passed:
class GFG {
public static void main(String[] args)
{
StringBuilder str
= new StringBuilder( "Tony Stark" );
try {
str.setCharAt(- 15 , 'A' );
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
Output:
java.lang.StringIndexOutOfBoundsException: String index out of range: -15
at java.lang.AbstractStringBuilder.setCharAt(AbstractStringBuilder.java:407)
at java.lang.StringBuilder.setCharAt(StringBuilder.java:76)
at GFG.main(File.java:16)
References:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#setCharAt(int, char)
Last Updated :
19 Aug, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...