java.lang.StringBuilder length()
Description
Notes:
- This method is specified by length in interface CharSequence.
Method Syntax
public int length()
Method Argument
Data Type | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns
The length() method returns the length of the sequence of characters currently represented by this object.
Compatibility
Requires Java 1.5 and up
Java StringBuilder length() Example
Below is a java code demonstrates the use of length() method of StringBuilder class. The example presented might be simple however it shows the behavior of the length() method.
package com.javatutorialhq.java.examples; import java.util.Scanner; /* * A java example source code to demonstrate * the use of length() method of StringBuilder class */ public class StringBuilderLengthExample { public static void main(String[] args) { // initialize the StringBuilder object StringBuilder sb = new StringBuilder(""); // 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 StringBuilder object System.out.println("Length of your name:"+sb.length()); s.close(); } }
The above java example source code demonstrates the use of length() method of StringBuilder 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 StringBuilder object, modify the contents of the StringBuilder object and printing the length of how many characters stored on the buffer.