Java String length: Find length of String in Java
The length() function is used to get the length of a String. Often, it is required to find out the length of a String, and for such scenarios, Java provides the inbuilt Java.lang.String.length() method. Length of the String is essentially the number of 16-bit Unicode characters it contains.
Java String length()
The string length() is a built-in function used to get the length of a Java String. The length() method returns the length of any string, which is equal to the number of 16-bit Unicode characters in the string. In the case of an empty String, it contains zero characters. However, in the case of a null string, this method will throw NullPointerException.
Syntax
See the following syntax of the String length().
public int length()
Return value
Several characters in the String.
Example
The following examples show the use of the length() method.
public class StrLen { public static void main(String[] args) { String str1 = "Millie Bobby Brown"; System.out.println(str1.length()); } }
See the output.
➜ java javac StrLen.java ➜ java java StrLen 18 ➜ java
NullPointerException
Let’s find the length of the null value of the string.
public class StrLen { public static void main(String[] args) { String str1 = null; System.out.println(str1.length()); } }
See the output.
➜ java javac StrLen.java ➜ java java StrLen Exception in thread "main" java.lang.NullPointerException at StrLen.main(StrLen.java:5) ➜ java
When calling length() method for a null String straight away throws a NullPointerException.
Demonstrates the use of the length() method for an empty String
See the following program of finding the length of the empty stringJavaJava.
public class StrLen { public static void main(String[] args) { String str1 = ""; System.out.println(str1.length()); } }
See the output.
➜ java javac StrLen.java ➜ java java StrLen 0 ➜ java
Demonstrates the use of length() method while iterating in a loop
See the following code.
public class StrLen { public static void main(String[] args) { String str1 = "El Camino"; for (int i = 0; i < str1.length(); i++) { System.out.println(str1.charAt(i)); } } }
See the output.
➜ java javac StrLen.java ➜ java java StrLen E l C a m i n o ➜ java
In the above example, the length() method has been used to determine how many times the loop should run to print all the characters of the String turn by turn. Here, the charAt(int i) method returns the character at index i.
This is how the length() method can be used in various programming constructs to obtain desirable outcomes.
What is the complexity of length() function in the String
It is 0(1) as the length is already known to String instance.
From JDK 1.6, it is visible.
public int length() { return count; }
It is essential to understand why they can cache the count value and keep using the same value for the count. The reason lies in the great decision when designing String, its Immutability.
That’s it for this tutorial.