Java String length() Method with Examples
Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are also a type of exceptional array that holds characters, therefore, strings are immutable as well.
The String class of Java comprises a lot of methods to execute various operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), substring() etc. Out of these methods, we will be focusing on the length() method.
What do you mean by Length or Size of a String?
The length or size of a string means the total number of characters present in it.
For Example: The string “Geeks For Geeks” has 15 characters (including spaces also).
The Java String length() method is a method that is applicable for string objects. length() method returns the number of characters present in the string. The length() method is suitable for string objects but not for arrays.
The length() method can also be used for StringBuilder and StringBuffer classes. The length() method is a public member method. Any object of the String class, StringBuilder class, and StringBuffer class can access the length() method using the . (dot) operator.
Method Signature: The method signature of the length() method is as follows –
public int length()
Return Type: The return type of the length() method is int.
Below are the examples of how to get the length of String in Java using the length() method:
Example 1: Java program to demonstrate how to get the length of String in Java using the length() method
The size of the String is 13
Example 2: Java program to illustrate how to check whether the length of two strings is equal or not using the length() method.
The length of both the strings are equal and is 3