Java StringBuilder length() method returns the length of the string. The StringBuilder instance represents a character sequence, the length() method returns the total number of characters present in this sequence.
The syntax of length() method is:
//returns the length of the character sequence //represented by StringBuilder instance sb sb.length()
length() Description
public int length(): Returns the total count of characters in character sequence represented by sb. Here, sb is an object of StringBuilder class.
length() Parameters
- It does not take any parameter.
length() Return Value
- Returns the length of String.
Example 1 of StringBuilder length() method
public class JavaExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Text");
System.out.println("Length of string 'text': "+sb.length());
//string with space, the whitespace is included in the count
StringBuilder sb2 = new StringBuilder("Sample Text");
System.out.println("Length of string 'Sample Text': "+sb2.length());
}
}
Output:

Example 2: Print length of user entered string
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
//take user input
System.out.print("Enter a string: ");
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
//append user input into sb
sb.append(str);
//print length
System.out.println("Length of entered string: "+sb.length());
}
}
Output:
