Java Tutorial-Java Arrays

Java Arrays


Basically Arrays in programming are used to store the multiple values in a single variable with indexing, instead of declaring the variables for each value.

To declare an array, we define the variable type with square brackets.



Example        

String colors[];

We can also declare the values in an array. To insert the value in Strings, we place the value in a comma-separated list, inside curly braces.


Example

String colors[]={"red", "orange", "pink", "brown"};

For example , to create an array of integers, we could write as

int num[] = {10, 20, 30, 40, 50};

 

Access the elements of an Array


The elements in an array can be accessed using the index number. The index number starts with the value ‘0’. If there are ‘n’ elements in an array, the index numbers will be 0,1,2,…n-1.

Example

String colors[]={"red", "orange", "pink", "brown"};
System.out.println(colors[2]);

Output

pink

 

Change an Array element


To change an element in an array, we refer to the index number.


Example

String colors[]={"red", "orange", "pink", "brown"};
colors[2] = "black";
System.out.println(colors[2]);

Output

black

To Loop through an Array


The array can be iterated using the for loop. The length property in array is used to specify how many times the loop should be executed.


Example

String colors[]={"red", "orange", "pink", "brown"};
for(int i=0; i<colors.length; i++){
       System.out.println(colors[i]);
}

Output

red
orange
pink
brown

Loop through an Array with For-each


There is a for-each loop, which is exclusively to loop through elements in an array.


Example

String colors[]={"red", "orange", "pink", "brown"};
for (String i : colors){
       System.out.println(i);
}

Output

red
orange
pink
brown

 

Multidimensional Arrays


A multidimensional array is an array which contains one or more array.

To create a two-dimensional array, we add each array in a set of curly braces within its own set of curly braces.


Example

int num[][] = {{10, 20, 30}, {40, 50,60}};

Here, the array num[][] is an array with a set of two arrays as its elements.

Indexes

There are two indexes in a multidimensional array, first one for the array and the second one for the element inside that array.


Example

int num[][] = {{10, 20, 30}, {40, 50,60}};
System.out.println(num[1][2]);

Here in the above example,   ‘1’ denotes the second array and ‘2’ denotes the third element in the second array. The index numbers starts from 0.

 

Loop through a Multidimensional Array


We use two for loops to loop through a Multidimensional array. Then for loop inside the for loop is used to loop through an each element in a multidimensional array.


Example

int num[][] = {{10, 20, 30}, {40, 50,60}};
for(int x=0; x<num.length; x++){
       for (int y=0; y<num[x].length; y++){
              System.out.println(num[x][y]);
       }
}

Output

10
20
30
40
50
60