Array in Java

An array is a special variable or container object. Unlike a variable holding just one value, an array can hold multiple values in a single type array container. All elements in an array have numeric index which is used to access their element value.

first indexsecondthirdfourthfifthsixthseventhlast index
01234567indices/keys
“zero”“one”“two”“three”“four”“five”“six”“seven”elements/values

Eg:

public class ArrayClass { int[] container; container = new int[8]; container[0] = 00; container[1] = 11; container[2] = 22; container[3] = 33; container[4] = 44; container[5] = 50; container[6] = 600; container[7] = 007; }

Here we have declared an integer array:

int[] container;

And allocate a memory for the elements:

container = new int[8];

At the end we have assigned the initial values started from zero up to eight.

Accessing the values of an array

In this example things might look different from the above example we sow but it is just another way of declaring, allocating and initializing array’s.

Eg:

 public class ArrayClass { public static void main(String[] args) { container = new int[8]; int[] container = { 00, 11, 22, 30 }; System.out.println(“Element value at index 0: ” + container[0]); } }

The example will printout the index values of zero on the screen. And we can do so for any element or index we want to access in our program.

Array of Arrays

Array of arrays or so called multidimensional array. An array which is, its components are arrays. An element should be accessed by a corresponding number of indexes

Eg:

public class ArrayOfArraysClass { public static void main(String[] args) { String[][] container ={ {“Male”, “Female”},{“Gentlemen”, “Ladies”} }; System.out.println(container[0][0] + container[1][0] + container[0][1]); } }

Here we have declared and assigned the multidimensional string type array in order to access its corresponding values as an index value.