setCharAt(): This method is available in java.lang.StringBuilder class of Java.
Syntax:
void java.lang.AbstractStringBuilder.setCharAt(int index, char ch)
This method takes two arguments one of type int and another of type char as its parameters. The character at the specified index is set to ch.
Note: The index argument must be greater than or equal to 0, and less than the length of this sequence.
Parameters: Two parameters are required for this method.
index: the index of the character to modify.
ch: the new character.
Throws:
StringIndexOutOfBoundsException - if index is negative or greater than or equal to length().
Approach 1: When the index is in the range.
Java
public class SetCharAt {public static void main(String[] args) {StringBuilder str = new StringBuilder("Hello World");int index = 2;char ch = 'X';str.setCharAt(index, ch);System.out.println(str);}}
Output:
HeXlo World
Approach 2: When the index is out of range.
Java
public class SetCharAt {public static void main(String[] args) {StringBuilder str = new StringBuilder("Hello World");int index = 15;char ch = 'X';str.setCharAt(index, ch);System.out.println(str);}}
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 15, length 11 at java.base/java.lang.String.checkIndex(String.java:3693) at java.base/java.lang.AbstractStringBuilder.setCharAt(AbstractStringBuilder.java:533) at java.base/java.lang.StringBuilder.setCharAt(StringBuilder.java:85)
No comments:
Post a Comment