java.lang.StringBuilder capacity()
Description
Method Syntax
public int capacity()
Method Argument
Data Type | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns
The capacity() method returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.
Compatibility
Requires Java 1.5 and up
Java StringBuilder capacity() Example
Below is a java code demonstrates the use of appendCodePoint() method of StringBuilder class. The example presented might be simple however it shows the behavior of the appendCodePoint() method.
package com.javatutorialhq.java.examples; import java.util.Scanner; /* * A java example source code to demonstrate * the use of capacity() method of StringBuilder class */ public class StringBuilderCapacityExample { public static void main(String[] args) { // initialize the StringBuilder object StringBuilder sb = new StringBuilder(""); System.out.println("Initial Capacity is " + sb.capacity()); // ask for user input System.out.print("Please enter any input:"); Scanner s = new Scanner(System.in); sb.append(s.nextLine()); s.close(); // print the length of StringBuilder contents System.out.println("Length after user input:" + sb.length()); System.out.println("capapcity after user input:" + sb.capacity()); sb.append("123183"); System.out.println("Current Length:" + sb.length()); System.out.println("New Capacity:" + sb.capacity()); } }
The above java example source code demonstrates the use of capacity() method of StringBuilder class. Initially the code displays the capacity of the StringBuilder without any characters on the buffer. And then this code takes a user input and then the program will display the new capacity. This source code is also good example in learning on how to initialize StringBuilder, and to modify the contents of the StringBuilder object.