Core Java Concepts and Syntax

Introduction to StringBuffer in Java

Introduction to StringBuffer in Java

Introduction

To build a mutable string object, utilize the StringBuffer class. It implies that it can be modified after creation. It stands for a character sequence that may be written and grown. Similar to Java's String class, which is also used to create strings, stringbuffer objects can be modified. Therefore, the StringBuffer class is used when we need to modify our string frequently. Additionally, it is thread safe, meaning that only one thread at a time can access it. StringBuffer has four constructors defined.

  1. StringBuffer(): It produces a string buffer that is empty and sets aside room for 16 characters.
  2. StringBuffer(int size): It produces a blank string and accepts an integer input to specify the buffer's capacity.
  3. StringBuffer(String str): From the specified string, a stringbuffer object is created.
  4. StringBuffer(charSequence []ch): From the charSequence array, a stringbuffer object is created.

Creating a StringBuffer Object

Using the StringBuffer class, we create a string buffer object in this example and test its mutability.

public class Demo {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("board");
System.out.println(sb);
// modifying object
sb.append("infinity");
System.out.println(sb);    // Output: studytonight

}
}

Output:

board boardinfinity

write your code here: Coding Playground

StringBuffer vs. String differences

In this example, we create and edit instances of the StringBuffer and String classes, but only the StringBuffer object is altered. See the illustration below.

class Test {
public static void main(String args[])
{
  String str = "board";
  str.concat("infinity");
  System.out.println(str);      // Output: study

  StringBuffer strB = new StringBuffer("board");
  strB.append("infinity");
  System.out.println(strB);    // Output: studytonight
}
}

board boardinfinity

write your code here: Coding Playground

Explanation:

Due to String objects' immutability, the output is what it is. Since the same String object won't be changed by concatenation, StringBuffer produces mutable instances instead. Consequently, it is modifiable.

Important methods of StringBuffer class

Some of the most frequently used methods of the StringBuffer class are those listed below.

append()

Any type of data's string representation will be placed at the end of StringBuffer object using this function. Multiple variants of the add() function are overloaded.

StringBuffer append(String str)
StringBuffer append(int n)
StringBuffer append(Object obj)

Each parameter's string representation is added to the StringBuffer object.

public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("test");
str.append(123);
System.out.println(str);
}
}

test123

insert()

One string is inserted into another using this procedure. Here are a couple variations on the insert() technique.

StringBuffer insert(int index, String str)
StringBuffer insert(int index, int num)
StringBuffer insert(int index, Object obj)

Here, the second argument's string representation is entered into the StringBuffer object while the first parameter specifies the index at which the string will be inserted.

public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("test");
str.insert(2, 123);
System.out.println(str);
}
}

test123

reverse()

A StringBuffer object's characters are reversed by this method.

public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);
}
}

olleH

replace()

By using the supplied start index and finish index, this function substitutes the string.

public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);
}
}


Hello java

capacity()

The StringBuffer object's current capacity is returned by this method.

public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );
}
}


16

There are 16 characters reserved for empty constructors. Consequently, the output is 16.

ensureCapacity()

The minimum StringBuffer object capacity is guaranteed using this approach. There won't be any change in capacity if the parameter to the ensureCapacity() function is smaller than the current capacity. The ensureCapacity() function will adjust the current capacity according to the following rule if the parameter is more than the current capacity:

(OldCapacity*2) Plus 2 equals newCapacity.
public class Demo {
public static void main(String[] args) {
StringBuffer str = new StringBuffer();
System.out.println( str.capacity()); 

//output: 16 (since empty constructor reserves space for 16 characters)
str.ensureCapacity(30); 

//greater than the existing capacity
System.out.println( str.capacity()); 

//output: 34 (by following the rule - (oldcapacity*2) + 2.) i.e (16*2)+2 = 34.
}
}


Output:

16 34



write your code here: Coding Playground