Java Array Length Tutorial With Code Examples

This Tutorial will Explain the Java Array Length attribute Along with its Various Uses and Different Situations in Which Array Length Attribute Can be Used:

In our previous tutorial, we explored the concept of printing of elements in Java array using various methods. As we know, in order to loop through the array we should know how many elements are there in the array beforehand so that we can stop when the last element is reached.

Thus we need to know the size or the number of elements present in the array for looping through the array.

Java doesn’t provide any method to calculate the length of the array but it provides an attribute ‘length’ that gives the length or size of the array.

Length of Array in Java

Java ‘length’ Attribute

The number of elements in the array during declaration is called the size or length of the array. Given an array named ‘myArray’, the length of the array is given by the following expression.

int len = myArray.length;

The program below shows the illustration of the length attribute of the Java array.

import java.util.*;
class Main
{
    public static void main(String[] args)
    {
        Integer[] intArray = {1,3,5,7,9};                  //integer array
        String[] strArray = { "one", "two", "three" };                        //string array

                //print each array and their corresponding length
        System.out.println("Integer Array contents: " + Arrays.toString(intArray));
        System.out.println("The length of the Integer array : " + intArray.length);

        System.out.println("String Array contents: " + Arrays.toString(strArray));
        System.out.println("The length of the String array : " + strArray.length);
    }
}

Output:

‘length’ attribute - Output

The program above simply makes use of the length attribute and displays the contents and length of two different arrays. Now that we have seen the length attribute, let us see how we can use it in different situations.

Array length is useful in several situations. Some of them are listed below.

They are:

  • To search for a specific value in the array.
  • Searching for minimum/maximum values in the array.

Let's discuss these in detail.

Searching For A Value Using Length Attribute

As already mentioned, you can iterate through an array using the length attribute. The loop for this will iterate through all the elements one by one till (length-1) the element is reached (since arrays start from 0).

Using this loop you can search if a specific value is present in the array or not. For this, you will traverse through the entire array until the last element is reached. While traversing, each element will be compared with the value to be searched and if the match is found then the traversing will be stopped.

The below program demonstrates searching for a value in an array.

import java.util.*;
class Main{
public static void main(String[] args) {
    String[] strArray = { "Java", "Python", "C", "Scala", "Perl" };           //array of strings
                //search for a string using searchValue function
    System.out.println(searchValue(strArray, "C++")?" value C++ found":"value C++ not found");
    System.out.println(searchValue(strArray, "Python")?"value Python found":"value Python not found");
}

private static boolean searchValue(String[] searchArray, String lookup)
{
    if (searchArray != null)     {
        int arrayLength = searchArray.length;      //compute array length
        for (int i = 0; i <= arrayLength - 1; i++)
        {
            String value = searchArray[i];                          //search for value using for loop
            if (value.equals(lookup)) {
               return true;
            }
        }
    }
return false;
}

Output:

Searching for a value using length attribute - Output

In the above program, we have an array of programming language names. We also have a function ‘searchValue’ which searches for a particular programming language name. We have used a for loop in the function searchValue to iterate through the array and search for the specified name.

Once the name is found the function returns true. If the name is not present or the entire array is exhausted then the function returns false.

Find The Minimum And Maximum Values In Array

You can also traverse the array using the length attribute and find the minimum and highest elements in the array.

The array may or may not be sorted. Hence in order to find the minimum or maximum elements, you will have to compare each of the elements till all the elements in the array are exhausted and then find out the minimum or maximum element in the array. We have presented two programs below.

This program is to find the minimum element in the array.

import java.util.*;
class Main {
    public static void main(String[] args) {
       int[] intArray = { 72,42,21,10,53,64 };        //int array
       System.out.println("The given array:" + Arrays.toString(intArray));
       int min_Val = intArray[0];                              //assign first element to min value
       int length = intArray.length;
       for (int i = 1; i <= length - 1; i++) //till end of array, compare and find min value
        {
            int value = intArray[i];
            if (value <min_Val) {
               min_Val = value;
            }
        }

    System.out.println("The min value in the array: "+min_Val);
    }
}

Output:

Find the minimum and maximum values in array - Output

In the above program, we have the first element in the array as a reference element. Then we compare all the elements one by one with this reference element and pick the smallest one by the time we reach the end of the array.

Note the way we use length attribute to iterate through the array.

The next program is used to find the largest element in the array. The logic of the program is on similar lines to that of finding the smallest element. But instead of finding the element less than the reference element, we find the element greater than the reference. This way, in the end, we get the maximum element in the array.

The program is as follows.

import java.util.*;
class Main {
   public static void main(String[] args) {
        int[] intArray = { 72,42,21,10,53,64 };        //int array
        System.out.println("The given array:" + Arrays.toString(intArray));
        int max_Val = intArray[0];                             //reference element
        int length = intArray.length;
        for (int i = 1; i <= length - 1; i++) // find max element by comparing others to reference
        {
        int value = intArray[i];
        if (value >max_Val) {
             max_Val = value;
            }
        }
       System.out.println("The highest value in the array: "+max_Val);
    }
}

Output:

Maximum element in the array - Output

Frequently Asked Questions

Q #1) What is the difference between the length of an array and the size of ArrayList?

Answer: The length property of an array gives the size of the array or the total number of elements present in the array. There is no length property in the ArrayList but the number of objects or elements in the ArrayList is given by size () method.

Q #2) What is the difference between length and length() in Java?

Answer: The ‘length’ property is a part of the array and returns the size of the array. The method length() is a method for the string objects that return the number of characters in the string.

Q #3) What is the length function in Java?

Answer: The length function in Java returns the number of characters present in a string object.

Q #4) How do you get the length in Java?

Answer: It depends on whether you want to get the length of the string or an array. If it’s a string then using length() method will give you the number of characters in the string.

If it is an array, you can use the ‘length’ property of the array to find the number of elements in the array.

Q #5) What is the maximum length of an array in Java?

Answer: In Java, arrays store their indices as integers (int) internally. So the maximum length of an array in Java is Integer.MAX_VALUE which is 231-1

Conclusion

This tutorial discussed the length property of arrays in Java. We have also seen the various situations in which length can be used.

The first and foremost use of the length attribute of the array is to traverse the array. As traversing an array endlessly may cause unexpected results, using for loop for a definite number of iterations can ensure that the results aren’t unexpected.

Happy Reading!!