Unit-2 Objects and Classes String Buffer(String Builder) Class
The String Builder/String Buffer class is an alternative to the String class. In general, a String Builder/String Buffer can be used wherever a string is used. String Builder/String Buffer is more flexible than String. You can add, insert, or append new contents into a String Builder or a String Buffer, whereas the value of a String object is fixed, once the string is created. The constructors and methods in StringBuffer and StringBuilder are almost the same.
String Builder class
Modifying Strings in the StringBuilder You can append new contents at the end of a string builder, insert new contents at a specified position in a string builder, and delete or replace characters in a string builder, using the methods listed below.
Append Method
Insert Method
Delete,reverse,replace,CharAt Method
The toString, capacity, length, setLength, and charAt Methods
Program //program of capacity and length function of string buffer. Class StringBufferDemo { Public static void main(String args[]) StringBuffer str=new StringBuffer(“java”); System.out.println(“length is:”+str.length()); System.out.println(“Capacity is:”+str.capacity()); } OutPut: Length is:4 Capacity is:20 Note: capacity function returns the number of characters in the string + 16 additional characters.
Program //program to convert the string “Great” to new string “God”. Class StringBufferDemo { Public static void main(String args[]) StringBuffer str=new StringBuffer(“Great”); str.setCharAt(1,’o’); str.setCharAt(2,’d’); Str.setLength(3); System.out.println(“New string is”+str); } OutPut: New string is:God