Home » Core Java » Java Array Length Example

About Prateek Sharma

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.

Java Array Length Example

In this post, we feature a comprehensive Java Array Length Example. The article talks about the length property of Arrays in Java and demonstrates its usage through some examples.

1. Introduction

Arrays are one of the most versatile data structure 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.

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

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 property 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

Since length is a member property of array so it can be used with all kinds of arrays. 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 case of the length property of arrays in Java is to prevent the ArrayIndexOutOfBoundsException. Lets 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 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 helps in determining the size of the array so as to provide the exit condition for the for-loop.

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, 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 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. The array property length 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
(+11 rating, 13 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of