You are on page 1of 9

OOP: Chapter 1- Fundamentals of Programming using Java

Handout #6 Introduction to Arrays

1. Array Basics

An array is a collection of variables of the same type, referred to by a common name. It is a group
of contiguous memory locations that all have the same name and the same type. Think of an array
as a "box" drawn in memory with a series of subdivisions, called elements, to store the data. The
box below could represent an array of 10 integers.
7 6 5 8 3 9 2 6 10 2
To refer to a particular location or element in the array, we specify the name of the array and the
position number (or index or subscript) of the particular element in the array. You put the index
between square brackets following the array name; for example, data[9] refers to the element in
the data array corresponding to the index value 9. The index for an array element is the offset of
that particular element from the beginning of the array. The first element will have an index of 0,
the second will have an index of 1, the third an index of 2, and the last subscript is 1 less than the
number used to declare the array. Thus, data[9] refers to the tenth element in the data array. The
index value does not need to be an integer literal. It can be any expression that results in a value
of type int that is equal to or greater than zero.

In Java, arrays can have one or more dimensions, although the one-dimensional array is the most
common. Arrays are used for a variety of purposes because they offer a convenient means of
grouping together related variables. For example, you might use an array to hold a record of the
daily high temperature for a month, a list of stock price averages, or a list of your collection of
programming books.

The principal advantage of an array is that it organizes data in such a way that it can be easily
manipulated. For example, if you have an array containing the incomes for a selected group of
households, it is easy to compute the average income by cycling through the array. Also, arrays
organize data in such a way that it can be easily sorted. Although arrays in Java can be used just
like arrays in other programming languages, they have one special attribute: they are implemented
as objects. By implementing arrays as objects, several important advantages are gained, not the
least of which is that unused arrays can be garbage collect.

2. Declaring Array Variables


To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Array variables indicate the type of object the
array will hold (just as they do for any variable) and the name of the array, followed by empty
brackets ([]). The general syntax for declaring an array is as follows: Here is the syntax for
declaring an array variable:
dataType[] arrayRefVar;
or
dataType arrayRefVar[]; // This style is allowed, but not preferred

The following are all typical array variable declarations:


String difficultWords[];
int temps[];

University of Gondar, Department of Computer Science Page 1


OOP: Chapter 1- Fundamentals of Programming using Java

double[] myList;
Statements such as those above do not create the array, they declare a variable and give it an
identifier just as if we declaring an instance variable; the only difference is the inclusion of the pair
of square brackets [ ] to indicate the variable is an array.
Note
 The style dataType[] arrayRefVar is preferred. The style datatype arrayRefVar[]
comes from the C/C++ language and was adopted in Java to accommodate C/C++
programmers.
 Unlike array declarations in several other programming languages (such as C and C++),
Java array declarations must not specify the number of array elements in the square
brackets after the array name; otherwise, a syntax error occurs. For example, the
declaration int c[ 12 ]; causes a syntax error.

3. Creating Arrays
Unlike declarations for primitive data type variables, the declaration of an array variable does not
allocate any space in memory for the array. Only a storage location for the reference to an array is
created. If a variable does not reference to an array, the value of the variable is null. You cannot
assign elements to an array unless it has already been created. After an array variable is declared,
you can create an array object and assign it to that variable. There are two ways to do this:
 Using new operator
 Directly initializing the contents of that array

The first way is to use the new operator to create a new instance of an array: Using the new operator
with the following syntax: arrayRefVar = new dataType[arraySize]; This statement does two things:
(1) it creates an array using new dataType[arraySize]; (2) it assigns the reference of the newly
created array to the variable arrayRefVar.
For example, String[] names = new String[10]; This line creates a new array of Strings with ten slots,
or elements. When you create the new array object using new, you must indicate how many
elements that array will hold. Array objects can contain primitive types such as integers or
booleans, just as they can contain objects: int[] temps = new int[99]; When you create an array object
using new, all its elements are initialized for you (0 for numeric arrays, false for boolean, ‘\0’ for character
arrays, and null for everything else).

Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];
Here is an example of such a statement: double[] myList = new double[10];This
statement declares an
array variable, myList, creates an array of ten elements of double type, and assigns its reference
to myList.

You can also create and initialize an array at the same time. Instead of using new operator to create
the new array object, enclose the elements of the array inside braces, separated by commas:
String[] names = { “Misganaw”, “Yihun”, “Maranata”, “Temesgen”, “Zeyneba” };
Each of the elements inside the braces must be of the same type and must be the same type as the
variable that holds that array. An array size of the number of elements you’ve included will be

University of Gondar, Department of Computer Science Page 2


OOP: Chapter 1- Fundamentals of Programming using Java

automatically created for you. This example creates an array of String objects named names that
contains five elements.
If you specify initializing values for an array, you must include values for all the elements. If you
want to set only some of the array elements to specific values explicitly, you must use an
assignment statement for each element for which you supply a value. For example:
int[] primes = new int[100];
primes[0] = 2;
primes[1] = 3;
When space for an array is allocated, the array size must be given, to specify the number of
elements that can be stored in it. Size can be obtained using arrayRefVar.length. For example,
myList.length is 10.

You can also initialize the elements in an array using a for loop to iterate over all the elements and
set the value for each:
double[] data = new double[50]; // An array of 50 values of type double
for(int i = 0 ; i<data.length ; i++) { // i from 0 to data.length-1
data[i] = 1.0;
}
4. Accessing Array Elements
You refer to an element of an array by using the array name followed by the element’s index value
enclosed between square brackets. An individual element within an array is accessed by use of an
index. An index describes the position of an element within an array. In Java, all arrays have zero
as the index of their first element. For example the names array described in the previous section
has 5 elements, it has index values of 0 through 4. To index an array, specify the number of the
element you want, surrounded by square brackets. Thus, the first element in names is names[0],
and the last element is names[4].
Example:
public class FirstArray{
public static void main(String[]args){
int []array=new int[10];
int i;
int sum=0;
double average=0.0;

for(i=0; i < array.length; i++) //initializing the array randomly


array[i]=(int)(10 * Math.random());

for(i=0; i < array.length; i++){ //computing the sum


sum+= array[i];
System.out.println("Array Element "+(i+1)+" = " + array[i]);
}

University of Gondar, Department of Computer Science Page 3


OOP: Chapter 1- Fundamentals of Programming using Java

if(sum != 0)
average=(double)sum/array.length; //computing the average

System.out.println("The Average is : "+average);


}
}
Using the for-each Loop with an Array
You can use the for-each style for loop as an alternative to the numerical for loop when you want
to process the values of all the elements in an array. The for-each style for eliminates the need to
establish a loop counter, specify a starting and ending value, and manually index the array. Instead,
it automatically cycles through the entire array, obtaining one element at a time, in sequence, from
beginning to end. For example:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums) sum += x;

With each pass through the loop, x is automatically given a value equal to the next element in nums. Thus,
on the first iteration, x contains 1, on the second iteration, x contains 2, and so on.

Here is an example program that demonstrates average of array elements rewritten using a for-each
version of the for:
public class ForEachLoop{
public static void main(String[]args){
double[] samples= {2.0, 3.0, 5.0, 7.0, 11.0, 13.0, 17.0}; // An array of 7 elements
double average = 0.0; // Variable to hold the average
for(double value : samples) {
average += value; // Sum all the elements
}
average /= samples.length; // Divide by the total number of elements
System.out.print(" The Average is : "+average);
}
}
The for loop will iterate through the values of all elements of type double in the samples array in
sequence. The value variable will be assigned the value of each element of the samples array in
turn. Thus, the loop achieves the same result as the numerical for loop that you used earlier: the
sum of all the elements will be accumulated in average. Of course, when you want to process only
data from part of the array, you still must use the numerical for loop with the loop counter ranging
over the indexes for the elements you want to access.
Note:
It’s important to remember that the for-each loop iterates over the values stored in an array. It does
not provide access to the elements for the purpose of setting their values. Therefore, you use it
only when you are accessing all the values stored in an array to use them in some way.

University of Gondar, Department of Computer Science Page 4


OOP: Chapter 1- Fundamentals of Programming using Java

5. Copying Arrays
You can copy one array variable into another, but then both variables refer to the same array:
Often, in a program, you need to duplicate an array or a part of an array. In such cases you could
attempt to use the assignment statement (=), as follows:
list2 = list1;
This statement does not copy the contents of the array referenced by list1 to list2, but merely
copies the reference value from list1 to list2. After this statement, list1 and list2 reference to the
same array. The array previously referenced by list2 is no longer referenced; it becomes garbage,
which will be automatically collected by the Java Virtual Machine.

In Java, you can use assignment statements to copy primitive data type variables, but not arrays.
Assigning one array variable to another array variable actually copies one reference to another
and makes both variables point to the same memory location.

There are four ways to copy arrays:


 Use a loop to copy individual elements one by one.
 Use the static arraycopy method in the System class.
 Use the clone method to copy arrays
 Use the copyOf method in the Arrays class

You can write a loop to copy every element from the source array to the corresponding element in
the target array. The following code, for instance, copies sourceArray to targetArray using a for
loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++) {
targetArray[i] = sourceArray[i];
}
Another approach is to use the arraycopy method in the java.lang.System class to copy arrays
instead of using a loop. The syntax for arraycopy is shown below:
arraycopy(sourceArray, srcPos, targetArray, tarPos, length);
The parameters srcPos and tarPos indicate the starting positions in sourceArray and
targetArray, respectively. The number of elements copied from sourceArray to targetArray is
indicated by length.
For example, you can rewrite the loop using the following statement:
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
The arraycopy method does not allocate memory space for the target array. The target array must
have already been created with its memory space allocated. After the copying takes place,
targetArray and sourceArray have the same content but independent memory locations.
Note
The arraycopy method violates the Java naming convention. By convention, this method should be
named arrayCopy (i.e., with an uppercase C).

If you actually want to copy all values of one array into a new array, you can also use the copyOf
method in the Arrays class: The syntax for this call is:

University of Gondar, Department of Computer Science Page 5


OOP: Chapter 1- Fundamentals of Programming using Java

dataType[] targetArray= Arrays.copyOf(sourceArray, sourceArray.length);


For example,
int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);
The second parameter is the length of the new array. A common use of this method is to increase
the size of an array:
luckyNumbers = Arrays.copyOf(luckyNumbers, 2 * luckyNumbers.length);
The additional elements are filled with 0 if the array contains numbers, false if the array contains
boolean values. Conversely, if the length is less than the length of the original array, only the
initial values are copied.
You can also clone an array using the clone method. For example, the following code
int[] list1 = {1, 2};
int[] list2 = list1.clone();
list1[0] = 7;
list2[1] = 8;
System.out.println("list1 is " + list1[0] + ", " + list1[1]);
System.out.println("list2 is " + list2[0] + ", " + list2[1]);
displays
list1 is 7, 2
list2 is 1, 8
6. Passing Arrays to Methods
When discussing arguments/parameters and methods, we talked about passing-by-value. Copies
of argument values are sent to the method, where the copy is manipulated and in certain cases, one
value may be returned. While the copied values may change in the method, the original values in
main did not change (unless purposely reassigned after the method).

The situation, when working with arrays, is somewhat different. If we were to make copies of
arrays to be sent to methods, we could potentially be copying very large amounts of data. Not very
efficient!
Passing an array mimics a concept called "pass-by-reference", meaning that when an array is
passed as an argument, its memory address location (its "reference") is used. In this way, the
contents of an array can be changed inside of a method, since we are dealing directly with the
actual array and not with a copy of the array.
Take the following code, for example:
public class Test {

University of Gondar, Department of Computer Science Page 6


OOP: Chapter 1- Fundamentals of Programming using Java

public static void main(String[] args) {


int x = 1; // x represents an int value
int[] y = new int[10]; // y represents an array of int values
m(x,y); // Invoke m with arguments x and y
System.out.println("x is " + x); Program Output
System.out.println("y[0] is " + y[0]);
}
public static void m(int number, int[]numbers){ x is 1
number = 1001; // Assign a new value to number y[0] is 5555
numbers[0] = 5555; // Assign a new value to numbers[0]
}
}

Anonymous Array
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For
example, the following method displays the elements in an int array:
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
You can invoke it by passing an array. For example, the following statement invokes the
printArray method to display 3, 1, 2, 6, 4, and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});
Note
The preceding statement creates an array using the following syntax: new dataType[]{value0,
value1, ..., valuek};
There is no explicit reference variable for the array. Such an array is called an anonymous array.
7. Returning an Array from a Method
You can pass arrays when invoking a method. A method may also return an array. For example,
the method shown below returns an array that is the reversal of another array:
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}

This program creates a new array result , copies elements from array list to array result and then
returns the array. For example, the following statement returns a new array list2 with elements 6,
5, 4, 3, 2, 1:
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);

University of Gondar, Department of Computer Science Page 7


OOP: Chapter 1- Fundamentals of Programming using Java

8. Multi-Dimensional Array
Up until now, all of our arrays have been one-dimensional arrays. These arrays have had "length",
but the "width" (or height) remained as only one cell. Although the one-dimensional array is the
most commonly used array in programming, multidimensional arrays (arrays of two or more
dimensions) are certainly not rare.

In Java, a multidimensional array is an array of arrays. A three dimensional array, for example,
has 3 subscripts, where each dimension is represented as a subscript in the array. Multidimensional
arrays use more than one index to access array elements. They are used for tables and other more
complex arrangements. While it is possible for arrays to have any number of dimensions, most
arrays are of one or two dimensions.
8.1.Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional arrays. Declaring a two-dimensional array in Java is
simple enough. For example, to declare a two-dimensional integer array table of size 10, 20 you
would write
int table[][]= new int[10][20];
In the next example, a two-dimensional array is loaded with the numbers 1 through 12.
// Demonstrate a two-dimensional array.
public class TwoD {
public static void main(String args[]) {
int t, i;
int table[][] = new int[3][4];
for(t=0; t < 3; ++t) {
for(i=0; i < 4; ++i) {
table[t][i] = (t*4)+i+1;
System.out.print(table[t][i] + " ");
}
System.out.println();
}}}
In this example, table[0][0] will have the value 1, table[0][1] the value 2, table[0][2] the value 3, and so
on. The value of table[2][3] will be 12. Conceptually, the array will look like that shown in the Figure
below.

Note
It is a common mistake to use table[2, 1] to access the element at row 2 and column 1. In Java,
each subscript must be enclosed in a pair of square brackets.

University of Gondar, Department of Computer Science Page 8


OOP: Chapter 1- Fundamentals of Programming using Java

Obtaining the Lengths of Two-Dimensional Arrays


A two-dimensional array is actually an array in which each element is a one-dimensional array.
The length of an array x is the number of elements in the array, which can be obtained using
x.length. x[0], x[1], ..., and x[x.length-1] are arrays. Their lengths can be obtained using
x[0].length, x[1].length, ..., and x[x.length-1].length.

For example, in the array table = new int[3][4], table[0], table[1], and table[2] are one-dimensional arrays
and each contains four elements, as shown in the figure above. table.length is 3, and table[0].length,
table[1].length, and table[2].length are 4.

8.2.Jagged/Ragged Arrays
So far, what you have seen is not too different from other programming languages. But there is
actually something subtle going on behind the scenes that you can sometimes turn to your
advantage: Java has no multidimensional arrays at all, only one-dimensional arrays.
Multidimensional arrays are faked as “arrays of arrays.”
Each row in a two-dimensional array is itself an array. Thus the rows can have different lengths.
An array of this kind is known as a ragged array. Here is an example of creating a ragged array:

As can be seen,
triangleArray[0].length is 5,
triangleArray[1].length is 4,
triangleArray[2].length is 3,
triangleArray[3].length is 2, and
triangleArray[4].length is 1.

If you don't know the values in a ragged array in advance, but you know the sizes, say the same
as before,you can create a ragged array using the syntax that follows:
int[][] triangleArray = new int[5][];
triangleArray[0] = new int[5];
triangleArray[1] = new int[4];
triangleArray[2] = new int[3];
triangleArray[3] = new int[2];
triangleArray[4] = new int[1];
You can now assign values to the array. For example,
triangleArray[0][3] = 50;
triangleArray[4][0] = 45;
Note
The syntax new int[5][] for creating an array requires the first index to be specified. The syntax
new int[][] would be wrong.

University of Gondar, Department of Computer Science Page 9

You might also like