How to calculate String Buffer capacity in Java?


The String class of the java.lang package represents a set of characters. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings objects are immutable, once you create a String object you cannot change their values, if you try to do so instead of changing the value a new object is created with the required value and the reference shifts to the newly created one leaving the previous object unused.

The StringBuffer (and StringBuilder) class is used when there is a necessity to make a lot of modifications to a String.

Unlike Strings, objects of type StringBuffer can be modified over and over again without leaving behind a lot of new unused objects. It is a thread-safe, mutable sequence of characters.

Example

 Live Demo

public class StringBufferExample {
   public static void main(String[] args) {
      StringBuffer buffer = new StringBuffer();
      buffer.append("Hello ");
      buffer.append("how ");
      buffer.append("are ");
      buffer.append("you");
      System.out.println("Contents of the string buffer: "+buffer);
   }
}

Output

Contents of the string buffer: Hello how are you

Calculating the StringBuffer capacity

The capacity of the StringBuffer denotes the number of characters in the StringBuffer.

Initially, every StringBuffer object is created with a fixed initial capacity of 16. You can also create a StringBuffer object with the required initial capacity bypassing the required integer value as a parameter as −

StringBuffer sb = new StringBuffer(225);

While appending data to the StringBuffer object, once you exceed the initial capacity the capacity of the StringBuffer object is increased.

The method named capacity() of the StringBuffer class returns an integer value representing the capacity of the StringBuffer(). Using this method you can find the capacity of the StringBuffer.

Example

The following Java program demonstrates how to finds the capacity of a StringBuffer object.

 Live Demo

public class StringBufferCapacity {
   public static void main(String[] args) {
      StringBuffer buffer = new StringBuffer();
      System.out.println("Initial capacity: "+buffer.capacity());
      buffer.append("Hello ");
      buffer.append("how ");
      buffer.append("are ");
      buffer.append("you");
      System.out.println("Contents of the string buffer: "+buffer);
      System.out.println("Capacity after adding data: "+buffer.capacity());
   }
}

Output

Initial capacity: 16
Contents of the string buffer: Hello how are you
Capacity after adding data: 34
raja
Published on 10-Sep-2019 17:08:26
Advertisements