java.lang.StringBuffer length()

Description :

This java tutorial shows how to use the length() method of StringBuffer class under java.lang package. The length method of StringBuffer class counts how many characters does the StringBuffer object has.

Method Syntax :

public StringBuffer length()

Parameter Input :

DataType Parameter Description
N/A N/A N/A

Method Returns :

The length() method simply returns the length (character count).

Compatibility Version :

Requires Java 1.0 and up

Java Code Example :

This java example source code demonstrates the use of length() method of StringBuffer class. Basically this code just takes a user input and then the program will display the character length of the user input. This source code is a good example in learning on how to initialize StringBuffer object, modify the contents of the StringBuffer object and printing the length of how many characters stored on the buffer.

package com.javatutorialhq.java.examples;

import java.util.Scanner;


/*
 * This example source code demonstrates the use of length()
 * of StringBuffer class
 */

public class StringBufferLength {

	public static void main(String[] args) {
		
		
        // initialize the StringBuffer object
        StringBuffer sb = new StringBuffer("");
        // ask for user input
        System.out.print("Please enter your name:");
        Scanner s = new Scanner(System.in);
        sb.append(s.nextLine());
        // print the number of characters of the string buffer object
        System.out.println("Length of your name:"+sb.length());

	}

}

Sample Output :

Running the example source code above will give you the following output

Please enter your name:Adam Sandler
Length of your name:12

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :