java.lang.StringBuffer capacity()
Description :
This java tutorial shows how to use the capacity() method of StringBuffer class under java.lang package. The capacity method of StringBuffer class gives the allowable number of characters this StringBuffer object can still accommodate.
Method Syntax :
public StringBuffer capacity()
Parameter Input :
DataType | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns :
This method returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.
Compatibility Version :
Requires Java 1.0 and up
Java Code Example :
This java example source code demonstrates the use of capacity() method of StringBuffer class. Initially the code displays the capacity of the StringBuffer 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 StringBuffer object, modify the contents of the StringBuffer object.
package com.javatutorialhq.java.examples; import java.util.Scanner; /* * This example source code demonstrates the use of capacity() * of StringBuffer class */ public class StringBufferCapacity { public static void main(String[] args) { // initialize the StringBuffer object StringBuffer sb = new StringBuffer(""); 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()); // print the length of string buffer contents System.out.println("Length after user input:"+sb.length()); System.out.println("capapcity after user input:"+sb.capacity()); sb.append("12345678"); System.out.println("Current Length:"+sb.length()); System.out.println("New Capacity:"+sb.capacity()); } }
Sample Output :
Running the capacity() method example source code of StringBuffer class will give you the following output
Initial Capacity is 16 Please enter any input:test string Length after user input:11 capapcity after user input:16 Current Length:19 New Capacity:34
Exception Scenario :
N/A
Similar Method :
- N/A