beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

StringBuilder.capacity() Method

By Chaitanya Singh | Filed Under: Java.lang.StringBuilder

Description

public int capacity(): Returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.

Example

This example demonstrate the use of capacity() method of StringBuilder class.

import java.lang.StringBuilder;
class StringBuilderCapacity{ 
  public static void main(String[] args) {
     StringBuilder sb = new StringBuilder("TEST STRING");
     /* Capacity of newly created StringBuilder instance
      * = length of string "TEST STRING" + 16
      * i.e 11+16 =27
      */
     System.out.println("Case1: Capacity: "+sb.capacity());
 
     StringBuilder sb2 = new StringBuilder();
     System.out.println("Case2: Capacity: "+sb2.capacity());
 
     StringBuilder sb3 = new StringBuilder("ABC");
     /* Capacity = length of String "ABC"=16
      * i.e 3+16 =19
      */
     System.out.println("Case3: Capacity: "+sb3.capacity());
 
  }
}

Output:

Case1: Capacity: 27
Case2: Capacity: 16
Case3: Capacity: 19

Enjoyed this post? Try these related posts

  1. StringBuilder.append(char c) Method
  2. StringBuilder.append(boolean b) Method
  3. StringBuilder.charAt() Method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap