Unit2 Objects and Classes String BufferString Builder Class

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 String. Buffer and String. Builder are almost the same.

String Builder class

String. Builder � 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, Char. At Method

The to. String, capacity, length, set. Length, and char. At Methods

Program //program of capacity and length function of string buffer. Class String. Buffer. Demo { Public static void main(String args[]) { String. Buffer str=new String. Buffer(“java”); System. out. println(“length is: ”+str. length()); System. out. println(“Capacity is: ”+str. capacity()); } } Out. Put: 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 String. Buffer. Demo { Public static void main(String args[]) { String. Buffer str=new String. Buffer(“Great”); str. set. Char. At(1, ’o’); str. set. Char. At(2, ’d’); Str. set. Length(3); System. out. println(“New string is”+str); } } Out. Put: New string is: God
- Slides: 10