Java StringBuilder.length() – Examples

In this tutorial, we will learn about the Java StringBuilder.length() function, and learn how to use this function to get the length of StringBuilder sequence, with the help of examples.

length()

StringBuilder.length() returns the length (character count) of this StringBuilder sequence.

ADVERTISEMENT

Syntax

The syntax of length() function is

length()

Returns

The function returns an integer.

Example 1 – length()

In this example, we will create a StringBuilder with some string passed as argument to constructor. We will then use length() method, to get the number of characters in the StringBuilder sequence.

Java Program

public class Example { 
    public static void main(String[] args) { 
        StringBuilder stringBuilder = new StringBuilder("abcdefg");
        
        int len = stringBuilder.length();
        System.out.println("Length is : " + len);
    }
}

Output

Length is : 7

Example 2 – length() – After append

In this example, we will take an empty StringBuilder, and append some values to it. We then find the length of the resulting StringBuilder sequence.

Java Program

public class Example { 
    public static void main(String[] args) { 
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(true);
        stringBuilder.append(2);
        stringBuilder.append(3.14);
        stringBuilder.append("abc");
        
        int len = stringBuilder.length();
        System.out.println("Sequence is : " + stringBuilder.toString());
        System.out.println("Length is   : " + len);
    }
}

Output

Sequence is : true23.14abc
Length is   : 12

Example 3 – length() – Empty sequence

In this example, we will take an empty StringBuilder, and find its length using length() method. We know, that the return value should be zero.

Java Program

public class Example { 
    public static void main(String[] args) { 
        StringBuilder stringBuilder = new StringBuilder();
        
        int len = stringBuilder.length();
        System.out.println("Length is : " + len);
    }
}

Output

Length is : 0

Conclusion

In this Java Tutorial, we have learnt the syntax of Java StringBuilder.length() function, and also learnt how to use this function with the help of examples.