StringBuilder length and capacity

In this chapter you will learn:

  1. How to get the length for a StringBuilder
  2. How to get the capacity for a StringBuilder

Get the length

int length() returns the length (character count).

public class Main {
  public static void main(String[] argv) {
    StringBuilder sb = new StringBuilder();
    sb.append("java2s.com");
//from  ja v  a2s .  c  om
    System.out.println(sb.length());
    System.out.println(sb.capacity());

    
    sb.trimToSize();
    
    System.out.println(sb.length());
    System.out.println(sb.capacity());
    
  }
}

The output:

Get the capacity

int capacity() returns the current capacity.

public class Main {
  public static void main(String[] a) {
    StringBuilder builder1 = new StringBuilder();
    StringBuilder builder2 = new StringBuilder(0);
    StringBuilder builder3 = new StringBuilder(100);
/*from  ja v  a2  s. c  om*/
    System.out.println(builder1.capacity());
    System.out.println(builder2.capacity());
    System.out.println(builder3.capacity());

  }

}

Output:

Next chapter...

What you will learn in the next chapter:

  1. How to get a single char from StringBuilder
  2. How to change a single char for StringBuilder
  3. How to delete a char at specified index
Home » Java Tutorial » String

String

    Java String type
    Java String Concatenation
    Java String Creation
    Java String Compare
    Java String Search
    Java String and char array
    Java String Conversion
    String trim, length, is empty, and substring
    String replace

StringBuffer

    StringBuffer class
    StringBuffer Insert and Append
    StringBuffer length and capacity
    StringBuffer char operation
    StringBuffer Operations
    Search within StringBuffer
    StringBuffer to String

StringBuilder

    StringBuilder
    StringBuilder insert and append
    StringBuilder length and capacity
    StringBuilder get,delete,set char
    StringBuilder delete, reverse
    StringBuilder search with indexOf and lastIndexOf
    StringBuilder to String

String Format

    Formatter class
    Format Specifier
    Format String and characters
    Format integer value
    Format decimal
    Scientific notation format
    Format octal and hexadecimal value
    Format date and time value
    Escape Formatter
    Minimum Field Width
    Specifying Precision
    Format Flags
    Uppercase Option
    Formatter Argument Index
    Align left and right
    Left and right padding a string

String Format Utilities

    Abbreviate string
    Caplitalize a string
    Uncapitalize a string
    Utility class for right padding
    Left padding
    Centers a String
    Transforms words