Java String length() Method
![Java Course - Mastering the Fundamentals](https://www.scaler.com/topics/images/instructor-tarun.webp)
The String class is a non-primitive class that allows us to access many inbuilt methods with the help of the String class object. The String class stores immutable characters. The String class uses the inbuilt length() method, which is implemented from the CharSequence interface to find string length in Java, i.e. the total number of characters present in the string.
Signature
Return Type
Integer—This method returns the string length in Java, which is the total number of characters present in the String object.
Internal Implementation
The string length in Java refers to the number of characters present in the string. It can be obtained using the length() method of the String class. The length of a string represents the total count of characters, including spaces and special characters. It is important to note that the length of a string is different from its capacity, which refers to the maximum number of characters that can be stored in the underlying data structure.
Java String length() Method Examples
Example 1 - Finding the String Length in Java
Output:
Example 2 - Finding the Length of a Character Array
Let's understand how to convert a char array to String format.
Output:
Explanation: When we pass the char array in the constructor of the String class, it converts all characters of the char array to a String format and returns it. That's why in the variable 'word', we get the String representation of the characters of the char array.
Example 3 - Finding the Length of a String Which Has Whitespaces
Output:
Explanation: The Output is 14 because the length() method includes the whitespace as well as other characters. The representation of the above String in char array is {'S', 'c', 'a', 'l', 'e', 'r', ' ', 't', 'o', 'p', 'i', 'c', 's',' '} . Whitespaces are also present in the char array.
Conclusion
- The String class uses the length() method to get the string length in java.
- The public access modifier prefixes the length() method.
- The length() method also includes the whitespace while calculating the length of the string.