.length()

garanews's avatar
Published Aug 22, 2022Updated Nov 5, 2022
Contribute to Docs

The .length() method returns the number of characters currently in the StringBuilder, whereas .capacity() returns the number of spaces available for characters in the StringBuilder.

Syntax

myStringBuilder.length()

The .length() method takes no arguments.

Example

The following example creates a StringBuilder with a specified String then displays the .length() of the StringBuilder before and after using the .delete() method to change its contents:

import java.util.*;
public class Example {
public static void main(String[] args)
{
StringBuilder str = new StringBuilder("Hello World!");
System.out.println(str.toString());
System.out.println(str.length());
str.delete(0,6);
System.out.println(str.toString());
System.out.println(str.length());
}
}

This produces the following output:

Hello World!
12
World!
6

All contributors

Contribute to Docs

Learn Java on Codecademy