Chapter 3 Arrays
Chapter 3 Arrays
Chapter 3 – Part 1
Arrays
Previously…
4
Declaring Array Variables
⮚ Purpose: to declare variables to reference arrays and specify
the type of array the variable can reference.
⮚ Two ways:
■ datatype[] arrayRefVar; //preferred style
Example: double[] myList;
■ datatype arrayRefVar[]; // not preferred
Example: double myList[];
Creating Arrays
⮚ The declaration of an array variable does not allocate any
space in memory for the array.
🡺The array variable only creates a storage location for the
reference to the array.
⮚ If the array variable does not refer to an array (i.e. the array
has not been created), the value of the array variable is null.
Eg: double[] myList;
myList
null
0 1 2 3 4 5 6 7 8 9
Combining Array Declaration and Creation
A shorthand notation which combines declaring and creating
arrays in a single statement.
Syntax
datatype[] arrayRefVar = new datatype[arraySize];
Example
double[] myList;
myList = new double[10]; double myList[] = new double[10];
myList
0 1 2 3 4 5 6 7 8 9
The Length of an Array
■ Once an array is created, its size is fixed and therefore,
cannot be changed.
■ In Java, the array’s size may be obtained using
arrayRefVar.length
For example,
Example
boolean[ ] myList = new boolean[10];
False False
… .. … … … … … False
Indexed Variables
■ In Java, array indexing is similar to C.
■ Array indices are 0-based, i.e. it starts from 0 to
arrayRefVar.length-1.
■ Each element in the array is represented using the
following syntax, known as an indexed variable:
arrayRefVar[index]
Example :
double[ ] myList = new double[10];
System.out.println(mylist[8]);
mylist
0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
Array Initializers
⮚ Declaring, creating and initializing in one step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
TestArray
15
Copying Arrays
⮚ Often, we need to duplicate an array or part of an array.
⮚ In Java, the assignment operator may be used to copy primitive
data type variables, but not arrays.
Example:
double[] myList = {1.9, 2.9, 3.4, 3.5};
double[] newList = myList; // does not copy
Copying Arrays
■ Assigning one array variable to another array variable copies
one reference to another and makes both variables point to the
same memory location :
list2 = list1;
Copying Arrays
Ways to copy arrays:
(a) Use a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
sourceArray 2 3 1 5 10
targetArray
for (int i = 0; i < sourceArrays.length; i++)
targetArray[i] = sourceArray[i];
18
Copying Arrays
(b) Use the arraycopy method from the java.lang.System
class
Syntax
arraycopy(sourceArray, src_position,
targetArray, target_position, length);
Example
System.arraycopy(oldArray, 0, newArray, 0,
oldArray.length);
⮚ The arraycopy method does not allocate memory space for the target
array, i.e. the target array must have already been created.
⮚ After copying, the target array and source array have the same content but
independent memory locations.
Exercise
Given the array declaration and creation statements
int[] arrayA = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] arrayB = new int[5];
int[] arrayC = new int[3];
int[] arrayD = new int[10];
write statements using the arraycopy method to
(a) Copy the first 5 elements of arrayA into arrayB.
System.arraycopy(arrayA, 0, arrayB, 0, 5);
(b) Copy the last 3 elements of arrayA into arrayC.
System.arraycopy(arrayA, 6, arrayC, 0, 3);
(c) Copy the middle 3 elements of arrayA into arrayD.
System.arraycopy(arrayA, 3, arrayD, 0, 3);
BACS2023 Object-oriented Programming
Chapter 3 – Part 2
Arrays
Learning Outcomes
At the end of this lesson, you should be able to
■ Develop and invoke methods with array arguments.
■ Explain the difference between passing primitive-typed
arguments and reference-typed arguments.
■ Develop and invoke methods with an array return value.
22
Passing Arrays to Methods
Invoke the method
int[] list = {3, 1, 2, 6, 4, 2};
printArray(list);
The statement
printArray( new int[]{3, 1, 2, 6, 4, 2}); 312642
creates an array using the following syntax:
new dataType[ ] { literal_0, literal_1, ..., literal_k };
There is no explicit reference variable for the array. Such array is called
an anonymous array.
Pass By Value
⮚ Java uses pass by value to pass arguments to a method.
▪ There are important differences between passing the value of variables of
primitive data types and passing arrays.
⮚ For a parameter of a primitive type value, the actual value is
passed.
■ Changing the value of the formal parameter inside the method does not
affect the value of the variable passed as argument in the method call.
⮚ For a parameter of an array type, the value of the parameter
contains a reference to an array; this reference is passed to
the method.
■ Any changes to the array that occur inside the method body will affect the
original array that was passed as the argument.
Pass By Value
public class Test {
public static void main(String[] args) {
int x = 1;
int[] y = new int[10];
m(x, y); // Invoke m with arguments x and y
System.out.println("x is " + x);
System.out.println("y[0] is " + y[0]);
}
public static void m(int number, int[] numbers) {
number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
}
Heap
The JVM stores the array in an area of memory, called heap, which is
used for dynamic memory allocation where blocks of memory are
allocated and freed in an arbitrary order.
public static void main(String[] args){
int[] a = {1, 2};
swap(a[0], a[1]);
swapFirstTwoInArray(a);
}
public static void swapFirstTwoInArray(int[] array){
int temp = array[0];
array[0] = array[1];
array[1] = temp;
}
public static void swap(int n1, int n2) {
int temp = n1;
n1 = n2;
n2 = temp;
}
28
Returning an Array from a Method
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
1 2 3 4 5 6 list
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
result[j] = list[i];
}
return result;
}
▪ ArrayMethods.java
Variable-Length Argument Lists (Optional)
public class VarargsDemo {
■ To pass a variable number of public static void main(String args[]) {
arguments of the same type to a printMax(34, 3, 3, 2, 55.5);
printMax(new double[]{1, 2, 3});
method, the parameter in the printMax();
method is declared as: }
33
Lengths of Two-dimensional Arrays (Optional)
array[4].length ArrayIndexOutOfBoundsException
Ragged Arrays (Optional)
▪ Each row in a two-dimensional array is itself an array. So, the rows
can have different lengths. Such an array is known as a ragged array.
For example,
int[][] matrix = {
{1, 2, 3, 4, 5}, 1 2 3 4 5 matrix.length is 5
{2, 3, 4, 5}, matrix[0].length is 5
2 3 4 5
{3, 4, 5}, matrix[1].length is 4
{4, 5}, 3 4 5
matrix[2].length is 3
{5} 4 5 matrix[3].length is 2
}; 5 matrix[4].length is 1
To Do
▪ Review the slides and source code for this chapter.
▪ Read up the relevant portions of the recommended text.
▪ Complete the remaining practical questions for this
chapter.
■ We shall selectively discuss them during class.
37