How to find the length of an array in java

ht‮ww//:spt‬w.lautturi.com
How to find the length of an array in java

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

The length field is a property of the array that holds the number of elements in the array. It is a final field, which means it cannot be modified after the array is created.

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

int[] numbers = {5, 3, 8, 1, 9, 4};
int length = numbers.length;
System.out.println("The length of the array is " + length);

In the above example, an array of integers is defined and initialized with six elements. The length field of the array is then accessed and stored in the length variable. The value of length is then printed to the console.

The output of this example will be "The length of the array is 6".

You can also use the length field to iterate over the elements of the array using a loop.

For example:

for (int i = 0; i < numbers.length; i++) {
  System.out.println("Element " + i + ": " + numbers[i]);
}

In this example, a for loop is used to iterate over the elements of the array. The loop continues as long as the value of the loop variable i is less than the value of numbers.length. The value of i is incremented by 1 after each iteration.

Inside the loop, the value of the element at the index i is printed to the console along with its position in the array.

Keep in mind that the length field only works for arrays. If you have an object that is not an array, you may need to use a different method to find its size. For example, you can use the size() method for List objects, or the length() method for String objects.

Created Time:2017-11-01 20:48:20  Author:lautturi