Java String length()

The Java String class length() method finds the length of a string. The length of the Java string is the same as the Unicode code units of the string.

Signature

The signature of the string length() method is given below:

Specified by

CharSequence interface

Returns

Length of characters. In other words, the total number of characters present in the string.

Internal implementation

The String class internally uses a char[] array to store the characters. The length variable of the array is used to find the total number of elements present in the array. Since the Java String class uses this char[] array internally; therefore, the length variable can not be exposed to the outside world. Hence, the Java developers created the length() method, the exposes the value of the length variable. One can also think of the length() method as the getter() method, that provides a value of the class field to the user. The internal implementation clearly depicts that the length() method returns the value of then the length variable.

Java String length() method example

FileName: LengthExample.java

Test it Now

Output:

string length is: 10
string length is: 6

Java String length() Method Example 2

Since the length() method gives the total number of characters present in the string; therefore, one can also check whether the given string is empty or not.

FileName: LengthExample2.java

Output:

String is not empty and length is: 10
String is empty now: 0

Java String length() Method Example 3

The length() method is also used to reverse the string.

FileName: LengthExample3.java

Output:

Reverse of the string: 'Welcome To JavaTpoint' is
tniopTavaJ oT emocleW

Java String length() Method Example 4

The length() method can also be used to find only the white spaces present in the string. Observe the following example.

FileName: LengthExample4.java

Output:

In the string: ' Welcome To JavaTpoint '
Total number of whitespaces present are: 4





Latest Courses