Arrays are one of the simplest data structures. Typically they are built-in to most modern programming languages. An array is an arrangement of data in a particular order. They map numbers (these are the indices of an array) to data items (the elements).

Here’s an image depicting what an array looks like conceptually:


Finer points of arrays:

The type of data stored inside of an array is declared in a programs source code when declaring the array. Some (often dynamically typed) programming languages allow for declaring arrays without specifying a particular data type. Traditionally arrays are defined to be a static (fixed) length that cannot be changed during the programs run time. Some programming languages allow for the length (the amount of items an array can contain) of an array to be changed during run-time. An array can be zero (indexes range from 0 to size-1) or one indexed (indexes range from 1 to size). Arrays can also be multi-dimensional (ie. 2, 3, or N dimensional). Arrays are often used to implement other data structures.

Advantages & Disadvantages of Arrays:


  • fast access for getting/setting elements
  • easy to use
  • efficient storage


  • fixed size
  • slow search

So without further ado lets get to some array examples!!!

Sample array usage in Java:

Sample declaration of an array of integers of size 10 named “arr”:

int[] arr = new int[10];

Alternate declaration style:

int[] arr = {4, 5, 6};

Sample declaration of an array of Strings of size 10:

String[] arr = new String[10];

Declare an array of integers of size 10 and set each index so that the index is equal to the element at that index:

int[] arr = new int[10];
for(int i = 0; i < 10; i++)
  arr[i] = i;

Get the element of the first index of an array of integers (arrays in Java are indexed starting at zero):

int element = arr[0];

Get the size of an array:

int size = arr.length;

Using the java.util.Arrays class to sort an array:

import java.util.Arrays;


Using the java.util.Arrays class and System.out.println() function to print out an array to the console:

import java.util.Arrays;

String s = Arrays.toString(arr);

Initialize a two dimensional array of size 8 by 9 and set all elements to 100:

int[][] marr = new int[8][9];
for(int i = 0; i < 8; i++)
	for(int j = 0; j < 9; j++)
		marr[i][j] = 100;

Initialize a three dimensional array of size 2 by 3 by 4 and set all elements to 25:

int[][][] threeDimensionalArray = new int[2][3][4];
for(int i = 0; i < 2; i++)
	for(int j = 0; j < 3; j++)
		for(int k = 0; k < 4; k++)
			threeDimensionalArray[i][j][k] = 25;

Data Structures