info@tutsfinder.in



Arrays in Java

Array is a collection of data of similar data type. Consider an example – If we say there is an array of Integer this means that we have a collection of data that contains only integer values.

Array uses static memory allocation. To access element from array you must have to mention its index value corresponding to the position of the element. We can easily access data in array.

The index of array always starts from 0.

But there is a disadvantage in array that we can store only fixed amount of elements. We cannot change size of an array at runtime. To overcome this problem, there is concept of Java Collections. Later in this tutorial we will study that.

There are two types of arrays –

1. One Dimensional

2. Multi Dimensional

Array Declaration and Initialization

If you want use array in your program then first declare variable and initialize the value to that variable.

Syntax: dataType array_name[]={ };

Example: int myarray [] = { 7,8,4,21};


Array First Program

class ArrayExample{
     public static void main(String args[]){
        int array[] = new int[5];
        for (int i=0;i<5;i++){
           array[i]=i+1;
       }
       for(int i=0;i<5;i++){
           System.out.println("array["+i+"] = "+array[i]);
       }
      
      }
}


Output:

array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5


Array Program to find the length of an array.

class ArrayLength
{
	public static void main(String[] args)
	{
		int arr[]={12,2,5,8,4,6,32};
		System.out.println("Length of an array is: "+arr.length);
	}
}



Output:


Length of an array is: 7