StringBuffer setCharAt() Method in Java: Usage and Examples
Table of Content:
To manipulate string, java.lang.StringBuffer class comes with many methods, otherwise,
which will take long laborious coding as in C/C++. One such method is setCharAt(int, char)
that replaces a single character in the string buffer. Now read setCharAt()
StringBuffer.
Syntax
void setCharAt(int where, char ch)
Parameters
where - specifies the index of the character being set,
ch - specifies the new value of that
character.
where must be nonnegative and must not specify a location beyond the end of the buffer.
Throws
IndexOutOfBoundsException
- if index is negative or greater than or equal to length().
Program
Following setCharAt() StringBuffer example illustrates.
public class DemosetCharAt { public static void main(String args[]) { StringBuffer sb1 = new StringBuffer("ABCDEFGHI"); System.out.println("Original string buffer sb1: " + sb1); sb1.setCharAt(0, 'a'); sb1.setCharAt(4, 'e'); System.out.println("String buffer sb1 after setting char: " + sb1); sb1.setCharAt(10, 'y'); } }
Output
Here is the output generated by this program:
Original string buffer sb1: ABCDEFGHI String buffer sb1 after setting char: aBCDeFGHI Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10 at java.lang.StringBuffer.setCharAt(StringBuffer.java:255) at DemosetCharAt.main(DemosetCharAt.java:14) Press any key to continue . . .
Program
// Demonstrate charAt() and setCharAt(). class SetCharAtDemo { public static void main(String args[]) { StringBuffer strng = new StringBuffer("Hello"); System.out.println("buffer before = " + strng); System.out.println("charAt(1) before = " + strng.charAt(1)); strng.setCharAt(1, 'i'); strng.setLength(2); System.out.println("buffer after = " + strng); System.out.println("charAt(1) after = " + strng.charAt(1)); } }
Output
Here is the output generated by this program:
buffer before = Hello charAt(1) before = e buffer after = Hi charAt(1) after = i Press any key to continue . . .