In Java, the length()
method of the String
class returns the number of characters in a string, including spaces and special characters. The syntax is:
This method is useful for validating input, looping through characters, or checking if a string is empty (str.length() == 0
). Unlike arrays, length()
for strings is a method, not a property (array.length
vs. string.length()
).
If the string is null
, calling length()
throws a NullPointerException
, so always check for null
before using it.