Core Java

Java Array Length Example

In this post, we feature a comprehensive Java Array Length Example. The article talks about the length property of Arrays, which is a public attribute and can be obtained by array.length, in Java and demonstrates its usage through some examples.

1. Introduction

Arrays are one of the most versatile data structures found in the programming paradigm, be it any programming language. An array is a group of similar datatype variables and all those variables are referred to by a single name which is the name of the array itself. So, instead of declaring multiple variable names for multiple variables, only one variable name would suffice to hold all the elements. This is particularly helpful when we want to perform similar processing on multiple variables of the same type.

You can watch the following video and learn how to use arrays in Java:

Java Array Example How to use Arrays in Java – Video

2. Arrays in Java

Unlike most programming languages, Java treats arrays a bit differently. Java allocates memory to an array dynamically.

Take a look at the below statement.

int[] a;        //Array Declaration

The above statement is how an array of integers is declared in Java. But Java doesn’t allocate any memory to it yet. It just creates a reference variable to hold that array. To actually allocate the memory to the array, it is initialized like below.

int[] a = new int[10];     //Array Declaration and Initialization
java array length

Arrays are allocated memory in Java only when they are initialized using the new keyword. This is attributed to the fact that Java treats arrays as objects and all objects are initialized using the new keyword in Java.

3. Java arrays length property

As arrays are treated as objects in Java, so arrays are powered by some member properties and methods. One of the most important properties is the length property which holds the value of the capacity of the array. The declaration of the length property provided intrinsically by Java is below.

public final field length;     //length may be positive or zero

In Java, since the length is a member property of array so it can be used with all kinds of arrays and it can be called by array.length. The objective of this property is to provide the size of the array i.e. the number of elements it can hold.

One of the most important use cases of the length property of arrays in Java is to prevent the ArrayIndexOutOfBoundsException. Let’s talk about it in more detail.

4. ArrayIndexOutOfBoundsException

Care has to be taken when dealing with arrays so as not to access any invalid index of the array. If the size of the array is n then the index is valid for the range [0, n-1]. If the code tries to access a negative index or an index greater than or equal to the size of array then Java throws ArrayIndexOutOfBoundsException.

An important point to note is that this exception is a Runtime exception. Java throws this exception only at runtime and there are not going to be any compilation issues. In order to avoid the ArrayIndexOutOfBoundsException, it is always safe to check if the index being accessed lies in the range [0, n-1]. Take a look at the below snippet.

int[] a = new int[]{1,2,3};
System.out.println(a[3]);     //throws ArrayIndexOutOfBoundsException

The above code snippet results in ArrayIndexOutOfBoundsException. The valid range for the above example is [0, 2]. Since the code tries to access the index 3 which is greater than 2, hence it results in the exception. To avoid this, modify the above code snippet as below.

int[] a = new int[]{1,2,3};
int i = 2;
if(0 < i && i < a.length){
    System.out.println(a[i]);     //prints 3 as a[2] is equal to 3
}

The above code snippet demonstrates the usage of length property to avoid the ArrayIndexOutOfBoundsException. The length property is extremely important when trying to perform some operation on all the elements of the array in a loop. Having a check if the index is less than the length of the array ensures the smooth functioning of the program without any exception.

5. Java array length examples

Example – 1

/* 
* This example demonstrates the usage of length property
* of array by calculating the sum of all elements of an 
* integer array.
*/ 

class Example1{

      public static void main(String[] args){

           int[] numberArray = new int[]{2,4,6,8,10};  //Array Declaration and initialization

           int sum = 0;                                //Variable to hold the sum 

           for(int i=0;i<numberArray.length;i++){      //numberArray.length return 5

              sum = sum + numberArray[i];   

           }
 
          System.out.println("Sum : "+sum);            //prints 30

      }

}

The above example calculates the sum of all the elements of an integer array by traversing all the elements of the array in a for-loop and adding the element in the variable sum. The length property is obtained by array.length and it helps in determining the size of the array so as to provide the exit condition for the for-loop in Java.

Example – 2

/* This example demonstrates the usage of length property
*  on a char array of vowels.
*/

class Example2{

      public static void main(String[] args){

           char[] vowels = new char[]{'a','e','i','o','u','A','E','I','O','U'};  //char array containing vowels

           char input = 'c';
           boolean isVowel = false;

           for(int i=0;i<vowels.length;i++){

              if(input == vowels[i]){
   
                 isVowel=true;
                 break;

              }

           }

           if(isVowel){

              System.out.println("It is vowel");

           }else{

              System.out.println("It is not vowel");

           }

      }

}

The above example checks if a character is a vowel or not. It declares and initializes a char array containing vowels. Then looping through the char array by using the java array.length property, it checks if the input is equal to current char being traversed in the array then it prints that the input char is a vowel. Otherwise, it prints it is not vowel.

6. Summary

This post was about the array.length property of arrays in Java. Started with a short description of array and what makes array different in Java. Further explained the property length and its usage by providing two examples. In Java, the array.length property is a great means when it is required to perform some operation on all the elements of array and provides the exit criteria for traversing the array. This is the most common use case of the length property.

6. Download the Source Code

This was an example of Java Array Length.

Download
You can download the full source code of this example here: Java Array Length Example

Prateek Sharma

Prateek has graduated in Computer Engineering from Thapar University (Patiala, India). He also holds a Master degree in Software Systems from Birla Institute of Technology & Science (Pilani, India). Currently he is working as a Full Stack Software Engineer in telecommunications sector where he is involved in multiple flavors of project ranging from development in J2EE,Groovy, JPA, Hibernate, Web Service (SOAP/REST) to DevOps tools like Jenkins, SonarQube, SonarLint, EclEmma etc. He also has experience in message queues like RabbitMQ and Kafka.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ankit
Ankit
4 years ago

EXCELLENT ARTICLE….NICELY WRITTEN….VERY HELPFUL TO ME…THNX

Prateek Sharma
Prateek Sharma
4 years ago
Reply to  Ankit

Thanks Ankit

Back to top button