Java String length() method

length() method tells us about the size of the string. In this post, we will discuss the length() method of the String class in detail.

  • Method declaration – public int length().
  • What does it do and return? It helps in returning the size of the string. The length equals the number of Unicode code units in the string.

Code Example –

public class Codekru {

	public static void main(String[] args) {

		String str = "codekru";
		System.out.println("Length of the string is: " + str.length());

	}
}

Output –

Length of the string is: 7

Yes, it’s that easy, and we don’t want to complicate it much. Now, let’s see some other scenarios.

Time complexity of the length() function of the String class

The time complexity of the length() function is O(1) as the String class has length as the field and returns the same when the length() function is used.

What will happen if we try to use the length() method on an empty string?

In this scenario, it will return the length of the string, which will be 0. Below is the code for the same.

public class Codekru {

	public static void main(String[] args) {

		String str = "";
		System.out.println("Length of the string is: " + str.length());

	}
}

Output –

Length of the string is: 0
What will happen if we try to use the length() method on a null String?

Yes, you guessed it right. Let’s see it with some code too. It will throw NullPointerException.

public class Codekru {

	public static void main(String[] args) {

		String str = null;
		System.out.println("Length of the string is: " + str.length());

	}
}

Output –

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null

So, we don’t recommend using it like this 😛

What if we try to use the length() method on a string that contains spaces?

length() method will also count the spaces within the String, as shown in the example below.

public class Codekru {

	public static void main(String[] args) {

		String str = "hello codekru";
		System.out.println("Length of the string is: " + str.length());

	}
}

Output –

Length of the string is: 13

If you want to learn more about Strings and its methods, we recommend you read this article.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected]

Liked the article? Share this on

Leave a Comment

Your email address will not be published.