Arrays
a. Definitions
b. Element access
c. Explicit initialisations
d. Multidimensional arrays
e. Enhanced for loop
An array is a collection of similar types of elements which have contiguous memory locations
referred to by a common name.We can store only a fixed set of elements in a Java array.
Arrays in Java are index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on the 1st index etc..
● Arrays are stored in contiguous memory [consecutive memory locations].
● Since arrays are objects in Java, we can find their length using the object property
length. This is different from C/C++, where we find length using sizeof.
● A Java array variable can also be declared like other variables with [] after the
data type.
● The variables in the array are ordered, and each has an index beginning from 0.
● Java arrays can also be used as a static field, a local variable, or a method
parameter.
● The size of an array must be specified by int or short value and not long.
● The direct superclass of an array type is Object.
● Every array type implements the interfaces Cloneable and java.io.Serializable.
● This storage of arrays helps us randomly access the elements of an array [Support
Random Access].
● The size of the array cannot be altered(once initialised). However, an array
reference can be made to point to another array.
An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a
class depending on the definition of the array. In the case of primitive data types, the actual
values are stored in contiguous memory locations. In the case of class objects, the actual
objects are stored in a heap segment. Below is an illustration of an array of integers:
Definitions
An array declaration has two components: the type and the name. type declares the element
type of the array. The element type determines the data type of each element that comprises
the array. There are two types of arrays, namely Single Dimensional Array and
Multidimensional Array.
Single dimensional arrays are arrays which have one row of data. They are also called one
dimensional arrays.Single dimensional arrays are declared as follows:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
For example:
String[] cars; // an array of strings, perhaps the name of the car
String []cars; // also a valid declaration
String cars[]; // also a valid declaration
Although the above declarations establish that cars is an array variable, no actual array exists.
It merely tells the compiler that this variable (cars) will hold an array of the string type. To
link cars with an actual, physical array of strings, a programmer must allocate one using new
and assign it to car as illustrated below:
cars = new String[15]; // an array of 15 strings
This above step is called instantiating an array. It is possible to declare and instantiate an
array is one statement:
String cars[] = new String[15];
To insert values into the array one can provide a comma separated list of elements between
braces. The values can be inserted after the instantiation step.
cars[0] = “Volvo”; //element number 1
Cars[1] = “Mazda” ; //element number 2
Initialisation can also be done in one step together with declaration and instantiation:
String cars[] = new String[4] {"Volvo", "BMW", "Ford", "Mazda"};
//this creates an array of 4 elements with values for each element initialised//
Arrays are accessed using the array name and array indices:
cars[2] = “Ford Ranger”; //asisgning a value to the 3rd element
System.out. println(cars[1]); //printing the 2nd element
Array Program Examples
Example 1
Public class StringArray {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
// access each array elements
System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);
System.out.println("Fifth Element: " + age[4]);
}
}
Example 2 - Accessing elements using for loop
public class StringArray {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
// loop through the array
// using for loop
System.out.println("Using for Loop:");
for(int i = 0; i < age.length; i++) {
System.out.println(age[i]);
}
}
}
Enhanced for loop
Another way to traverse arrays is to use the enhanced for loop statement. This is the for-
each statement. The syntax is as follows:
for (data-type var : array)
{
statements using var;
}
The for-each loop traverses the array or collection until the last element. For each element, it
stores the element in the variable and executes the body of the for-each loop.
//An example of Java for-each loop
public class IntegerArray{
public static void main(String args[]){
//declaring an array
int arr[]={12,13,14,44};
//traversing the array with for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
// Java program to illustrate
// for-each loop
public class Marks
{
public static void main(String[] arg)
{
{
int[] marks = { 125, 132, 95, 116, 110 };
int highest_marks = maximum(marks);
System.out.println("The highest score is " + highest_marks);
}
}
public static int maximum(int[] numbers)
{
int maxSoFar = numbers[0];
// for each loop
for (int num : numbers)
{
if (num > maxSoFar)
{
maxSoFar = num;
}
}
return maxSoFar;
}
}