Java programming course: 6.1 Arrays, loops, and sorts

In the previous lesson we looked at arithmetic operations on primitives.


Arrays, loops, and sorts

Arrays provide a simple means of grouping like objects that they can be processed as a whole. Loops enable you to repeat parts of your code a certain number of times, while sorting enables you to modify the sequence in which groups of objects are processed.

In this section you will learn:

  • How to use single-dimensional and multi-dimensional arrays
  • How to loop over the elements in an array
  • How to sort the elements of an array into a particular sequence

Arrays

An array is a collection of objects or primitives of a particular type, capable of being referenced by the individual items that comprise that array. Each item in an array, whether an object or a primitive, is known as an element. Arrays are specified using square brackets [] with the number of elements required given inside the brackets. The number of elements must be defined before the array is first used and may not be changed thereafter.

An example of using a primitive array would be If you need to store the average temperature values for each of the twelve months of a year (assuming the temperatures are rounded to the nearest integer), then you could declare and instantiate an array with twelve int elements:

// Define array of temperatures for 12 months
int[] monthlyTemperatures = new int[12];
 

Note the following:

  • int[] declares that you are defining an array of int primitives
  • monthlyTemperatures is the variable name of the array. It is conventional (though not required) to name variables which represent a collection of items in the plural form
  • new int[12] declares that there should be 12 elements in the array (to represent each of the 12 months)
  • Each of the 12 individual elements will default to a value of zero, because that is the default value for int

An example of an object array would be If you wanted to store details of four animals, then you could declare and instantiate an array with four Animal elements:

// Define array of four Animal objects
Animal[] animals = new Animal[4];
 

Note the following:

  • Animal[] declares that you are defining an array of Animal objects
  • animals is the variable name of the array
  • new Animal[4] declares that there should be 4 elements in the array
  • Each of the 4 individual elements will default to null, i.e., no actual Animal objects have been instantiated yet

To access a particular element within an array you specify the required index (that is, its element number) inside square brackets. Index values start from zero and go up to one less than the number of elements:

// The following values will each be zero at this stage
int january	 = monthlyTemperatures[0];
int february	 = monthlyTemperatures[1];
int march	 = monthlyTemperatures[2];
int april	 = monthlyTemperatures[3];
int may	 = monthlyTemperatures[4];
int june	 = monthlyTemperatures[5];
int july	 = monthlyTemperatures[6];
int august	 = monthlyTemperatures[7];
int september = monthlyTemperatures[8];
int october	 = monthlyTemperatures[9];
int november  = monthlyTemperatures[10];
int december  = monthlyTemperatures[11];
 

To change the value of a particular element you reference it using its index. For example, to set the temperature for March to 8 its index will be 2:

// Set temperature for March
monthlyTemperatures[2] = 8; // index 2 is third element in array
 

Object arrays are used in the same way, but each element is null until it is specifically instantiated:

// The following references will each be null at this stage.
Animal firstAnimal	= animals[0];
Animal secondAnimal = animals[1];
Animal thirdAnimal  = animals[2];
Animal fourthAnimal = animals[3];
 

You need to instantiate each element as appropriate:

// Create objects for each element in animals array
animals[0] = new Lion("Leo", Gender.MALE, 3);
animals[1] = new Monkey("Bonzo", Gender.MALE, 2);
animals[2] = new Penguin("Petra", Gender.FEMALE, 1);
animals[3] = new Penguin("Oswald", Gender.MALE, 4);
 

Note that for object arrays you can instantiate a subclass of the declared type, as shown above, where each array element is declared as type Animal but contain a Lion, Monkey or Penguin object.

To invoke a method on an object element of an array, specify the required element number after the variable name:

// Get name of first animal in the array
String name = animals[0].getName();
 

If you attempt to access an element of an array using a non-existent index (such as -1 or 4, above) you will receive an ArrayIndexOutOfBoundsException at runtime. Similarly, if you try to access a method of an element of a reference type array before an object has been instantiated for that element you will receive a NullPointerException at runtime. It is the programmer's responsibility to ensure this is prevented.

The number of elements defined for an array is specified once and cannot be changed thereafter. If you need to change the number of elements you would have to copy each element to a different array, but this might suggest that it would be better to use one of the classes from the Java collections framework, such as ArrayList, rather than using an array.

The Java collections framework will be covered in Section 11.

There is a short-cut technique that lets you declare an array together with its values by listing them inside braces and separated by commas:

int[] numbers = {14, 896, -28};
String[] sentence = {"words", "in", "a", "sentence"};
Animal[] pets = {new Lion("Leo", Gender.MALE, 3),
                 new Penguin("Percy", Gender.MALE, 2)};
 

In each case the first listed item becomes element zero, the second becomes element one, etc.

Note how you still need to use the new keyword when instantiating each object in the pets example above.

Multi-dimensional arrays

The arrays shown so far are examples of single-dimensional arrays, but Java allows you to define arrays with any number of dimensions. For example, to model a two-dimensional array of integer values corresponding to ten rows of 5 columns, you could declare and instantiate an array, and then access elements of it, as follows:

// 10 rows, 5 columns
int[][] tabularData = new int[10][5];

// Set value for third row, fifth column
tabularData[2][4] = 123; // remember, indexes start from 0
 

Two-dimensional arrays tend to be used for tabular data. An example might be for recording monthly values over separate years, where the first dimension is the year and the second dimension is the months. While Java supports any number of dimensions, it is unusual to need more that two.


In the next lesson we will continue our zoo example by making use of an array.

Next lesson: 6.2 Example class using an array


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Saturday, 13 December 2025

Captcha Image