how to find length of string array java

‮w‬ww.lautturi.com
how to find length of string array java

To find the length of a string array in Java, you can use the length field of the array.

Here's an example of how to find the length of a string array in Java:

String[] words = {"apple", "banana", "orange"};

int length = words.length;

System.out.println("The length of the array is " + length);

In the above example, an array of strings is created with three elements. The length field of the array is then accessed and stored in the length variable. The length variable is then printed to the console.

Note that the length field is a final field, which means it cannot be modified. It is also not a method, so it cannot be called with parentheses.

Keep in mind that the length field returns an int value, which means it can only return lengths up to the maximum value of an int (2147483647). If you need to handle arrays with larger lengths, you can use the long data type or the java.math.BigInteger class.

For example:

import java.math.BigInteger;

String[] words = {"apple", "banana", "orange"};

BigInteger length = BigInteger.valueOf(words.length);

System.out.println("The length of the array is " + length);

In this example, the length field of the array is accessed as an int value, which is then converted to a BigInteger object using the valueOf() method. The BigInteger object is then stored in the length variable and printed to the console.

Created Time:2017-11-01 20:42:52  Author:lautturi