setCharAt(): This method is available in java.lang.StringBuffer class of Java.
Syntax:
void java.lang.StringBuffer.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. This sequence is altered to represent a new character sequence that is identical to the old character sequence, except that it contains the character ch at position index.
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) {StringBuffer str = new StringBuffer("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) {StringBuffer str = new StringBuffer("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.StringBuffer.setCharAt(StringBuffer.java:293)
No comments:
Post a Comment