Arrays – One Dimensional and Two Dimensional

An array is analogous to a basket of different colored marbles, each occupying the same space, placed next to each other in the basket, having the same shape, but identifiable by their different colors.

 In Java, an array is nothing but an object that holds multiple elements of a single data type under a common variable name. These multiple elements stored under one variable name are indexed to specify their individual locations in the contiguous memory allocated. However, only a fixed set of elements can be stored in a Java array.

The length of an array is established at the time of its creation and is unchangeable post creation. The length property can be used to find the number of elements stored in an array. Each element in the array can be accessed using its numerical index, beginning with 0.

All the above said elements are accessed on Index basis, in order to access the very first element, we need to access 0th location and in order to access the last element we need to access the (n-1) location.

We will be discussing following 2 types of array supported by Java-

  1. One Dimensional Array
  2. Two Dimensional Array

One Dimensional Array

As mentioned above, a one dimensional array is a sequential collection of variables having the same datatype. We can store various elements in an array .

Now, let us try to understand how can we perform different operations on array

a. Declaring Array

dataType [] variableName or datatype variableName[] ;

where,

datatype – The type of Data that the array will be holding, it determines the type of each element .Like an array of int, char, float , double , etc.

variableName– It’s the name of the array , from which you want to identify the array.

[] (square brackets) –Thy are used to denote an array.

public class Test {

	byte byteArrayName[];
	short shortsArrayName[];
	boolean booleanArrayName[];
	long longArrayName[];
	float floatArrayName[];
	double doubleArrayName[];
	char charArrayName[];

	// OR

	byte[] byteArrayName1;
	short[] shortsArrayName1;
	boolean[] booleanArrayName1;
	long[] longArrayName1;
	float[] floatArrayName1;
	double[] doubleArrayName1;
	char[] charArrayName1;

}


b. Instantiating an Array

dataType [] variableName  – This statement only declared an array, i.e only a reference is created.

In order to give memory to the array, we have to create or instantiate the array as below:

variableName= new dataType[size]

The above syntax, perform following 3 operations:

  • Creates a new array of dataType[size]
  • Assign the memory to the array with the help of the new keyword.
  • Size represents the number of elements we want to store in an array.

We can declare and instantiate the arrays in one single statement as shown below:

datatype variableName=new datatype[size]

c. Assigning Values to any array

We can follow either of the way to assign values to the array


class Test {

	public static void main(String args[]) {

		int[] arrayName= {1,2,3,4,5};

		//OR the following way
		
		int[] usingNewKeyword = new int[4];
		usingNewKeyword[0]=1;
		usingNewKeyword[1]=1;
		usingNewKeyword[2]=1;
		usingNewKeyword[3]=1;
		
	}
}

d. Representation of One Dimensional Array

1D arrays are stored in the following manner:

Two Dimensional Array

Till now we have seen how to work with the single dimensional arrays.

Now let’s discuss about, Two dimensional array. It is arranged as an array of arrays. The representation of the elements is done in the form of rows & columns.

a. Declaring a Two Dimensional Array

datatype[][] variableName

where,

datatype – The type of Data that the array will be holding, it determines the type of each element. Like an array of int, char, float, double, etc.

variableName– It’s the name of the array, from which you want to identify the array.

[][] – This is the symbol that shows the difference between the One Dimensional & Two Dimensional arrays.

The main difference between the One Dimensional and Two-dimensional array is [][],i.e  We have two square brackets that help us in storing the data in the form of rows and columns.

b. Instantiating a Two Dimensional Array

With the following syntax, we can initialize the Two dimensional array.

variableName=new int[rowSize][columnSize]

where,

[rowSize][columnSize] – It is used to define so as of how many no. of elements will be stored in a two-dimensional array, in the form of rows and columns.

c. Assigning Values to a Two dimensional array

dataType[][] variableName ={
		{Row0valueColumn0Value, Row1valueColumn1Value ,…},
		{Row1valueColumn0Value, Row1valueColumn1Value ,…},
		.
		.
		.
		   }

Example –


class Test {

	public static void main(String args[]) {

		 int[][] variableName = { { 1, 2 }, { 3, 4 } };
	}
}

d. Representation of Two Dimensional Array

2D arrays are stored in the following format in the system:

Accessing 1D and 2D Array elements

Till now we have seen the ways to instantiate and assign the values to a different kind of array, but in the real environment, we need to access and manipulate these values which will help us in the multiple transactions.

Since all the elements in the array, let it be 1D or 2D, they are of the same data type. Due to this reason we usually use for loop to traverse the array and perform different operations in them.

  • Traversing or Accessing 1D array

With the following line of code, we could easily access or traverse through the ID array.


class Test {

	public static void main(String args[]) {

		int[] arrayName= {10,20,30,40,50}; //Declare , initialize , Assigned values
		
	for(int i=0;i<arrayName.length;i++) //Processing or Accessing each element of array
	{
		System.out.println("Elemet "+ i + " is :"+ arrayName[i]);
	}
		
	}
}

Output –

Elemet 0 is :10
Elemet 1 is :20
Elemet 2 is :30
Elemet 3 is :40
Elemet 4 is :50

We are using the for loop, in order to iterate the Array that we created in the introduction section.

The arrayName.length is used to calculate the array size at the runtime.

  • Traversing or Accessing 2D array

class Test {

	public static void main(String args[]) {

		 int[][] arrayName = { { 10, 20 }, { 30, 40 } }; 
		  
	        for (int i = 0; i < arrayName.length; i++) { 
	            for (int j = 0; j < 2; j++) { 
	                System.out.println("Element at "+"Row"+i+"Column"+j+" is "+arrayName[i][j] + " "); 
	            } 
	  
	            System.out.println(); 
	        } 
	        
	        System.out.println("Internally they are being stored like this.....");
	        for (int i = 0; i < arrayName.length; i++) { 
	            for (int j = 0; j < 2; j++) { 
	                System.out.print(arrayName[i][j] + " "); 
	            } 
	  
	            System.out.println(); 
	        } 
	    
	}
}

Over here we are using 2 for loops in order to iterate the two dimensional array.

The first loop that is mentioned as follows:

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

It is used to iterate, the rows in the 2D array.

And the following condition is helping us to iterate the columns in the array.

                   for (int j = 0; j < 2; j++)

Both the for Loop needs to go hand in hand, since we are traversing each row and all the columns in it, one by one.

Output-

Element at Row0Column0 is 10 
Element at Row0Column1 is 20 

Element at Row1Column0 is 30 
Element at Row1Column1 is 40 

internally they are being stored like this.....
10 20 
30 40 

In this article, we have discussed the basics of 1D array and 2D array. And Learnt how to access the members of the array.

Tejasvi Nanda

About the Author

Tejasvi Nanda