How to Find the Length of a String or Array in Java



Java






In this article, we show how to find the length of either a string or an object in Java.

To find the length, you simply take the string or the array and follow it with a dot and the keyword length.

This finds the length of the string or array.

Finding the Length of a String

To find the length of the string, you simply take the string in double quotes or the variable representing the string and follow it with a dot and the keyword length(). For a string, length must be length() and not just simply length.

You want to store the output of this function in an integer in Java, because the output of this length() function is a string.

The code below shows how to do this.



So this is all that is required to find the length of a string in Java.

We create a string named animal and set it equal to "pig".

We then create an integer named lengthanimal which stores the length of the string in animal. This lengthanimal variable is set equal to animal.length(). This finds the length of the string in the animal variable.

We then output the length, which in this case will be 3.

Java Output

The length is 3.


If you want to take the length of the string directly without it being in a variable, then you would take the string in double quotes and follow it with a dot and the keyword() length.

This would be shown in the following code.



So when giving the string in directly, this is the way you would do it.

Java Output

The length is 3.




Finding the Length of an Array

So now we'll show how to find the length of an array in Java.

So to do so, we take the array name, follow it with a dot, and the keyword() length. This time the parentheses, (), are not included.

This is shown in the code below.



So above we create an array of Strings named animals. We then initialize 5 values.

If you want, you could create an integer variable to store this length, but it isn't required to do this.

We then output the length of the array.

Java Output

The length is 5.

And this is how we can find the length of strings or arrays with Java.

HTML Comment Box is loading comments...