![](./write-blog/images/141866839-length-method-in-java.png)
Java String length() Method: Usage and Examples
☰Fullscreen
Table of Content:
The length of a string is the number of characters that it contains. To obtain the length of a string, call the length( ) method, shown below:
Syntax
public int length()
Parameters
No Parameter
Specified by
length in interface CharSequence
Returns
Returns the number of characters present in the buffer.
Following example uses length() StringBuffer method to count the characters existing in the StringBuffer object.
Program
public class StringBufferMethodDemo { public static void main(String args[]) { StringBuffer sb1 = new StringBuffer(); // empty buffer (no characters) System.out.println("Number of characters in sb1 (empty buffer): " + sb1.length()); StringBuffer sb2 = new StringBuffer("Hello"); // buffer with some data System.out.println("\nNumber of characters in sb2 (with data Hello): " + sb2.length()); sb2.append("World"); int newLength = sb2.length(); System.out.println("Number of characters in sb2 after appending World: " + newLength); } }
Output
Number of characters in sb1 (empty buffer): 0 Number of characters in sb2 (with data Hello): 5 Number of characters in sb2 after appending World: 10 Press any key to continue . . .
Program
public class StringBufferLength { public static void main(String args[]) { char chars[] = { 'a', 't', 'n' }; String s = new String(chars); System.out.println(s.length()); } }
Output
3 Press any key to continue . . .