web analytics

Java Arrays

Java Arrays are data structures which can store multiple values or objects of same data type. In case of variables we need to declare a variable for each value or object. Java Arrays can be one dimensional or multi-dimensional.
A one-dimensional array can be declared in multiple ways as follows:

Datatype [] arrayName ;
Datytype[] arrayName ;
Datatype arrayName[] ;

When an array is declared, only a reference of array is created. To actually create or assign memory to array, we need to instantiate array as follows:

int arrayName[] ; // declaration of array
arrayName = new int [10] ; // allocation of memory to array

The above statements will create reference of array named arrayName of type integer. It will also assign 10 memoray locations to arrayName of type integer. Now we can store ten integers at that locations using the reference arrayName.
Now we can assign values to this array as follows:

arrayName[0]=10;
arrayName[1]=20;
.
.
.
.
.
arrayName [9]=100;

We can create and assigned values to arrays as follows:

int[] numbers = {1,3,4,6,8} ;
String[] vehicles= {"Car", "Truck", "Jeep", "Bus"};

Loop Through an Array with For loop.

We can loop through the array elements using the for loop, and length property to specify how many times the loop should run.

Example

Following example prints all elements of a string array:

String[] vehicles= {"Car", "Truck", "Jeep", "Bus"};
for (int i = 0; i < vehicles.length; i++) {
System.out.println(vehicles[i]);
}

Array and for-each loop

For-each loop iterates each element of array without using index of array. Following is an example of looping through an array using for-each loop:

String[] vehicles= {"Car", "Truck", "Jeep", "Bus"};
for (String vehicle : vehicles) {
System.out.println( vehicle );
}