In Java, the length of an array refers to the number of elements the array can hold. You can access this length using the .length
property. This is a built-in property provided by Java for all arrays.
Fine Java Array Length Program
package com.javacodepoint.array.basic;
// Java program to Find Length of an Array
public class ArrayLengthExample {
// main method
public static void main(String[] args) {
// Declare and initialize an array
int[] numbers = { 10, 20, 30, 40, 50 };
// Find the length of the array
int length = numbers.length;
// Print the length of the array
System.out.println("The length of the array is: " + length);
}
}
OUTPUT:
The length of the array is: 5
Code Explanation:
- Array Declaration and Initialization:
int[] numbers = {10, 20, 30, 40, 50};
Here, we declare an array of integers with 5 elements.
- Accessing the Array Length:
int length = numbers.length;
The.length
property gives the total number of elements in the array.
- Printing the Length:
System.out.println("The length of the array is: " + length);
This outputs the value oflength
.
Key Points:
.length
is a property for arrays, not a method. So, it doesn’t have parentheses (i.e., no.length()
).- The indexing of arrays starts at 0 but
.length
gives the total count of elements (not the highest index).
Read Also: Get Array Input | Find the Sum of an Array