How to find String length in java string method

Get String length with String length() method

To find String length in java there is a method length().

This method is used to get the length of the string.

The signature of length method is:

The length method returns the length of the string. it counts the number of Unicode in string.

str.length java Example

This is a very simple way to get the length of a string in java.

Output

Finding the length of unicode string in java

Here we are considering the Hindi language stored in String. We use length() to get the string length.

You can take any Unicode character to check length string length() works properly.

Output

Finding the String length in java of unicode characters

Here we have stored a Unicode value in String and found its length.

Output

Using toCharArray() to find String length in java

toCharArray() is another method in the String class to convert String to a character array.

Signature of toCharArray() is

In the above program String is converted to a character array using toCharArray().

Character array has a field length. This length property finds the length of the character array.

Output

Using Function to find the length

In the above program, you find the length of the Java String in the main method.

Here we have created two static methods length() and length1().

these two methods are accepting string and getting its length.

You can also use command line argument to get the string at run time.

Using Recursion to find length

Here we are using recursion to find the length of the string.

When a function is called it is checking the length of the string if the string is empty then return zero else calls again itself by adding one to the return value.

On each recursive call, we are eliminating the first character from the string.

Create your own string length method in java

Output

Hope you learn and understand how to get the length of a string as we discussed different ways to find string length.

substring length java

Substring length can also be found the same was as any string length.

call length method on substring subString.length()

Q: how to calculate length of a string in java

Ans: Java String class has an inbuilt method length(). From this method, we can get the length of a string.

Another way is by manually counting the number of characters in the string (using loops).

Keep Reading other topics.