Arrays

Definition

An array is a fixed-length collection of data elements of a single data type. You can create an array of integers, an array of longs, an array of floats, an array of doubles, an array of characters, an array of strings, etc. The length of an array is fixed at the time of its creation.

An element in an array is accessed by means of its index (position in the array). The first element in an array is referenced by [0], the second element by [1], etc. The index must be enclosed in square brackets ([]).

The following image shows the score array consisting of 5 data elements (length = 5 ; elements are numbered from 0 to 4) to store the points obtained by my students for the programming class:

The index of an array starts with [0]. The first element is [0], the second element is [1], the third element is [2], etc.

Declaration of an Array

An array is implemented as an object (new operator). An array object always contains the member variable length. This variable is set to the size of the array when the array is created.

In general, an array can be created as follows:

With two statements:

dataType[] arrayName;
arrayName = new dataType[size];

With one statement:

dataType[] arrayName = new dataType[size];
Examples:

int[] score;
score = new int[5];

String[] names = new String[10];

Access Elements in an Array

Elements in an array can be accessed as follows:

arrayName[index] = expression;

The data type of index must be a byte, short or int value, variable or result of a mathematical expression.

The data type of the index value must be byte, short or int.
Examples:

score[0] = 12;
score[1] = 17;
score[2] = 8;
score[3] = 11;
score[4] = 10;

An array can be declared and initialised in one statement:

dataType[] arrayName = {list of values};
Examples:

int[] score = {12,17,8,11,10};
String[] names = {"Lars", "Anna", "Laura", "Nathan", "Elise"};

Size of an Array

The size of an array is available from de length member variable:

arrayName.length;
Example:

score.length;
lengthis a member variable not a method: brackets are not allowed!

How to Pass an Array to a Method?

In the following example we will develop a class to print an array, to search the minimum and maximum value in an array and to calculate the average of all elements in an array. These methods are members of a class called ArrayMethods.

ArrayMethods

//ArrayMethods
//Carlos De Backer
public class ArrayMethods{
   private int[] score;
   
   public ArrayMethods(int[] points){
      score = points;
   }
   public void printArray(){
      int index;
      for (index=0;index<score.length;index++){
         System.out.print(score[index]+ " ");
      }
      System.out.println(" ");
   }
   public int minArray(){
      int minimumValue;
      int index;
       minimumValue = score[0];
      for (index=1;index<score.length;index++){
            if (score[index]<minimumValue){
                minimumValue=score[index];
         }
      }
      return (minimumValue);
   }
   public int maxArray(){
      int maximumValue;
      int index;
       maximumValue = score[0];
      for (index=1;index<score.length;index++){
         if (score[index]>maximumValue){
             maximumValue=score[index];
         }
      }
      return (maximumValue);
   }
   public float averageArray(){
      float sum=0.0;
      int index;
      for (index=0;index<score.length;index++){
         sum = sum + (float)score[index];
      }
      return sum/(float)score.length;
   }
}

The private member variable score is declared to be an int[] array. As you may remember from the previous lesson the variable score is only a reference variable to an array object. The array object itself is not initialised yet (no new operator).

The constructor public ArrayMethods(int[] points) receives a reference variable called points to an int[] object created in another class (class ArrayExamples). In this constructor we assign the reference variable points to the member variable score (score = points). This is the initialisation of the score member variable. Both variables refer now to the same memory space.

The methods printArray(), minArray(), maxArray() and averageArray() access all elements in the array called score by means of the int variable called index. The for statement (for (index=0; index<score.length;index++)) loops through all elements in the array starting from 0 to score.length.

ArrayExamples

The main() method is available in the class ArrayExamples:

//ArrayExamples
//Carlos De Backer
public class ArrayExamples{
   public static void main (String[] args){
      int[] pointsJava = {4,8,5,8,16,18,10,9,13,10,18,13,7,15,11,16,10,8,20,5};
       ArrayMethods scoresJava = new ArrayMethods(pointsJava); 
       scoresJava.printArray();
       System.out.println("Minimum: "+scoresJava.minArray());
       System.out.println("Maximum: "+scoresJava.maxArray());
       System.out.println("Average: "+scoresJava.averageArray());
      
      int[] pointsHTML = {14,16,11,17,8,15,12,18,7};
       ArrayMethods scoresHTML = new ArrayMethods(pointsHTML);
       scoresHTML.printArray();
       System.out.println("Minimum: "+scoresHTML.minArray());
       System.out.println("Maximum: "+scoresHTML.maxArray());
       System.out.println("Average: "+scoresHTML.averageArray());
   }
}
4 8 5 8 16 18 10 9 13 10 18 13 7 15 11 16 10 8 20 5  
Minimum: 4
Maximum: 20
Average: 11.2
14 16 11 17 8 15 12 18 7  
Minimum: 7
Maximum: 18
Average: 13.111111

Exam results for the Java class are stored in the array named pointsJava and the results for the HTML class are stored in the array pointsHTML. Two objects are created from the class ArrayMethods: scoresJava and scoresHTML. The arrays pointsJava and pointsHTML are used as arguments to the constructor ArrayMethods. The methods printArray(), minArray(), maxArray() and averageArray() have been called for both objects.

How to Return an Array from a Method?

//ReturnExamples
//Carlos De Backer
public class ReturnExamples{
   public static void main(String[] args){
      int[] pointsJava = {4,8,5,8,16,18,10,9,13,10,18,13,7,15,11,16,10,8,20,5};
      float[] percentageJava = calculatePercentage(pointsJava);
      
      int index;
      for (index=0;index<pointsJava.length;index++){
         System.out.println(pointsJava[index]+"    "+percentageJava[index]+"%");
      }
   }
   private static float[] calculatePercentage(int[] points){
      int index;
      float[] percentageArray = new float[points.length];
      for(index=0;index<points.length;index++){
         percentageArray[index]=(float)points[index]/(float)20.0*(float)100.0;
      } 
      return percentageArray;  
   }
}
4     20.0%
8     40.0%
5     25.0%
8     40.0%
16    80.0%
18    90.0%
10    50.0%
9     45.0%
13    65.0%
10    50.0%
18    90.0%
13    65.0%
7     35.0%
15    75.0%
11    55.0%
16    80.0%
10    50.0%
8     40.0%
20    100.0%
5     25.0%

The method calculatePercentage(int[] points) receives an int [] array named points from the main() method. The method calculates, for all points in the array, the percentage achieved by the student (the maximum result that can be achieved is 20). All percentages are stored in a new float [] array called percentageArray. The length of the percentageArray is the same length as the length of the points array (float [] percentageArray = new float [points.length]). The return statement returns percentageArray to the main() method. The main() method receives the percentageArray and stores the percentages in a float [] array named percentageJava.

It is possible to use a variable to define the size of an array.

Multi-dimensional Arrays

The following statement can be used to declare a two-dimensional array of strings with 3 rows and 2 columns:

String names[][] = new String [3][2];

The first index refers to rows, the second index refers to columns. The following example illustrates the use of two-dimensional arrays:

//StringArrays
//Carlos De Backer
public class StringArrays{
   public static void main(String[] args){
      String [][] names = new String[3][2];
      names[0][0] = "John";
      names[0][1] = "Paris";
      names[1][0] = "Elisabeth";
      names[1][1] = "Brussels";
      names[2][0] = "Jeffrey";
      names[2][1] = "Washington";
     int row;
     for (row=0;row<names.length;row++){
         System.out.println(names[row][0]+" lives in "+names[row][1]);
      }
   }
}
John lives in Paris
Elisabeth lives in Brussels
Jeffrey lives in Washington