length() StringBuffer Example

November 28, 2014 | class StringBuffer
StringBuffer comes with many utility methods to do operations on strings apart String class own methods. One such method is length() StringBuffer.

StringBuffer class comes with two methods - length() to find the number of characters present in the buffer and capacity() method to know the buffer size.

Following is the length() StringBuffer method signature as defined in Java API.

  • public int length(): Returns the number of characters present in the buffer.
Following example uses length() StringBuffer method to count the characters existing in the StringBuffer object.
public class StringBufferMethodDemo
 public static void main(String args[])
  StringBuffer sb1 = new StringBuffer();             // empty buffer (no characters)
  System.out.println("Number of characters in sb1 (empty buffer): " + sb1.length()); 

  StringBuffer sb2 = new StringBuffer("Hello");      // buffer with some data
  System.out.println("\nNumber of characters in sb2 (with data Hello): " + sb2.length()); 

  int newLength = sb2.length();
  System.out.println("Number of characters in sb2 after appending World: " + newLength); 

length() StringBuffer Output screenshot on length() StringBuffer Example

1. Also refer capacity() to find the buffer capacity (or storing capability) of StringBuffer object. 2. There is similar method length() in String class to find the number of characters.