Accessing Elements and Length Attribute in Arrays

In this class, We discuss Accessing Elements and Length Attribute in Arrays.

The reader should have prior knowledge of array declaration. Click Here.

Example:

The below diagram shows the code for accessing elements in an array.

class test

{

public static void main()

{

int[] a = {1,2,5,10};

int i;

for(i=0;i<4;i++)

{

System.out.println(a[i]);

}

}

We use a loop to access elements in an array.

The loop variable “i” is used to point to the index of an array.

a[i] where i = 0,1,2,3.

The below diagram shows the elements in random access memory.

a = 2000 is the starting memory address of the array.

a[0] is 2000 + 0*4 = 2000

The zeroth element is located in 2000 location.

a[1] is 2000 + 1*4 = 2004

The one position element is located in the 2004 position.

In the above way, we find the index location.

For all array objects, we have a length attribute.

The length attribute gives the size of the array.

a.length is 4.