0
0
Javaprogramming~15 mins

Array length property in Java

Choose your learning style8 modes available
menu_bookIntroduction

The array length property tells you how many items are in the array. It helps you know the size of the array so you can use it safely.

When you want to loop through all items in an array without going out of bounds.
When you need to check if an array is empty before processing it.
When you want to create a new array or data structure based on the size of an existing array.
regular_expressionSyntax
Java
public class ArrayLengthExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int lengthOfArray = numbers.length;
        System.out.println("Length of array: " + lengthOfArray);
    }
}

The length property is not a method, so it does not use parentheses.

It works only with arrays, not with other collections like ArrayList.

emoji_objectsExamples
line_end_arrow_notchThis shows the length of an empty array, which is 0.
Java
int[] emptyArray = {};
System.out.println(emptyArray.length);
line_end_arrow_notchArray with one element has length 1.
Java
int[] singleElementArray = {10};
System.out.println(singleElementArray.length);
line_end_arrow_notchArray with three elements has length 3.
Java
int[] numbers = {5, 10, 15};
System.out.println(numbers.length);
code_blocksSample Program

This program creates an array of scores, prints all the scores, and then prints the length of the array using the length property.

Java
public class ArrayLengthDemo {
    public static void main(String[] args) {
        int[] scores = {85, 90, 78, 92, 88};
        System.out.println("Array before processing:");
        for (int index = 0; index < scores.length; index++) {
            System.out.print(scores[index] + " ");
        }
        System.out.println();
        System.out.println("Length of the array: " + scores.length);
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Accessing the length property is very fast, it takes constant time O(1).

line_end_arrow_notch

The length property uses a small fixed amount of memory, so space complexity is O(1).

line_end_arrow_notch

A common mistake is to try to use length() with arrays, but length is a property without parentheses.

line_end_arrow_notch

Use length when you need the fixed size of an array. For dynamic collections, use size() method instead.

list_alt_checkSummary

The length property tells you how many elements are in an array.

It is used without parentheses, unlike methods.

Knowing the length helps you avoid errors when accessing array elements.