Java StringBuffer length() Method
Last Updated : 09 Dec, 2024
Improve
The length() method in the StringBuffer class is used to retrieve the number of characters currently in a StringBuffer object. It helps determine the current size of the character sequence in the buffer.
Example 1: Here, we are using the length() method to retrieve the number of characters in a StringBuffer object.
// Java program to demonstrate length() method
public class StringBufferLength {
public static void main(String[] args) {
// Create a StringBuffer object with a string
StringBuffer sb = new StringBuffer("Hello, GFG");
System.out.println("" + sb.length());
}
}
Output
10
Syntax of length()
Method
public int length()
- Parameter: None.
- Return Type: int (returns the length of the StringBuffer object).
Example 2: In this example, we will use the length() method to reflects all the changes after modifying the StringBuffer.
// Java program to demonstrate length()
// after modifications
public class StringBufferLength {
public static void main(String[] args) {
// Create a StringBuffer object
StringBuffer sb = new StringBuffer("Java Programming");
// Print the initial length of the StringBuffer
System.out.println("" + sb.length());
// Append a string to the StringBuffer
sb.append(" Language");
System.out.println("" + sb.length());
}
}
Output
16 25
Example 3: This example demonstrates how length() behaves for an empty StringBuffer object.
// Java program to demonstrate length() with
// an empty StringBuffer
public class StringBufferLength {
public static void main(String[] args) {
// Create an empty StringBuffer object
StringBuffer sb = new StringBuffer();
// Print the length of the empty StringBuffer
System.out.println("" + sb.length());
}
}
Output
0
Example 4: Here, we will use the length() method to perform conditional checks on the content of a StringBuffer.
// Java program to use length()
// for conditional checks
public class StringBufferLength {
public static void main(String[] args) {
// Create a StringBuffer object with a string
StringBuffer sb = new StringBuffer("Java Programming");
// Check if the StringBuffer is empty
if (sb.length() == 0) {
System.out.println("StringBuffer is empty.");
} else {
System.out.println("StringBuffer is not empty. Length: "
+ sb.length());
}
}
}
Output
StringBuffer is not empty. Length: 16