Thursday, January 30, 2025
HomeProgrammingJava String length() Method

Java String length() Method

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:

java
String str = "Hello World";
int length = str.length(); // 11

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()).

See also  What are the top 10 programming languages?

If the string is null, calling length() throws a NullPointerException, so always check for null before using it.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x