Module6-String Builder Class
Module6-String Builder Class
The StringBuilder append() method concatenates the given argument with this string.
class StringBuilderExample{
The StringBuilder insert() method inserts the given string with this string at the given
position.
class StringBuilderExample2{
System.out.println(sb);//prints HJavaello
class StringBuilderExample3{
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
The delete() method of StringBuilder class deletes the string from the specified
beginIndex to endIndex.
class StringBuilderExample4{
sb.delete(1,3);
System.out.println(sb);//prints Hlo
class StringBuilderExample5{
sb.reverse();
System.out.println(sb);//prints olleH
The capacity() method of StringBuilder class returns the current capacity of the Builder.
The default capacity of the Builder is 16. If the number of character increases from its
current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your
current capacity is 16, it will be (16*2)+2=34.
class StringBuilderExample6{
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
The ensureCapacity() method of StringBuilder class ensures that the given capacity is
the minimum to the current capacity. If it is greater than the current capacity, it
increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16,
it will be (16*2)+2=34.
class StringBuilderExample7{
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70