Java StringBuilder get and set capacity and length

Description

Java StringBuilder get and set capacity and length

// StringBuilder length, setLength, capacity and ensureCapacity methods.

public class Main 
{
   public static void main(String[] args)
   {/*from   ww w .j  a  v  a 2 s  .co  m*/
      StringBuilder buffer = new StringBuilder("Hello, how are you?");

      System.out.printf("buffer = %s\nlength = %d\ncapacity = %d\n\n",
         buffer.toString(), buffer.length(), buffer.capacity());

      buffer.ensureCapacity(75);
      System.out.printf("New capacity = %d\n\n", buffer.capacity());

      buffer.setLength(10);
      System.out.printf("New length = %d\nbuffer = %s\n", 
         buffer.length(), buffer.toString());
   } 
}



PreviousNext

Related