0% found this document useful (0 votes)
51 views

Chapter 3 Arrays

Here are the key steps: 1. Declare a method that returns an array: public static int[] reverse(int[] list) { 2. Inside the method, create a new array to hold the reversed values: int[] reversed = new int[list.length]; 3. Populate the new array with values from the original array in reverse order: for (int i = 0; i < list.length; i++) { reversed[i] = list[list.length - i - 1]; } 4. Return the new reversed array: return reversed; } So the method takes an array as a parameter, reverses the
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Chapter 3 Arrays

Here are the key steps: 1. Declare a method that returns an array: public static int[] reverse(int[] list) { 2. Inside the method, create a new array to hold the reversed values: int[] reversed = new int[list.length]; 3. Populate the new array with values from the original array in reverse order: for (int i = 0; i < list.length; i++) { reversed[i] = list[list.length - i - 1]; } 4. Return the new reversed array: return reversed; } So the method takes an array as a parameter, reverses the
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

AACS2204 Object-Oriented Programming Techniques

Chapter 3 – Part 1

Arrays
Previously…

⮚ You have already learnt about arrays in c or c++


programming. This chapter will cover only the aspects of
arrays in Java which are different from c or c++.
⮚ For a more complete review of arrays, refer to Appendix A5.
Learning Outcomes
At the end of this lesson, you should be able to :
⮚ Declare, create, initialize and use arrays in Java
programs.
⮚ Simplify programming for arrays using foreach loops.
⮚ Apply the use of the arraycopy method to copy
contents from one array to another.
Recall what are arrays
Array is a data structure that represents a collection of the
same types of data.

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

⮚ Array elements cannot be assigned to an array unless the


array has already been created.
Creating Arrays
■To create an array, use the new operator.
■Syntax:
arrayRefVar = new datatype[arraySize];
Example:
myList
null
double[] myList;

myList = new double[10];


myList

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,

double myList[] = new double[10];


int length = myList.length;
Default Values
■ When an array is created, its elements are assigned
the default value of
■ 0 for the numeric primitive data types
■ '\u0000' for char typed array elements
■ false for boolean typed array elements

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};

⮚ The new operator is not required.


⮚ The above shorthand notation is equivalent to the following
statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

myList 1.9 2.9 3.4 3.5


CAUTION
⮚ Using the shorthand notation, you have to declare,
create, and initialize the array all in one statement.
double[] myList = {1.9, 2.9, 3.4, 3.5};

⮚ Splitting it would cause a syntax error. For example, the


following is wrong:
double[] myList;
myList = {1.9, 2.9, 3.4, 3.5};
Enhanced for Loop: foreach Loop
⮚ The foreach loop enables you to traverse the complete array
sequentially without using an index variable.
Syntax:
for (elementType value: arrayRefVar) {
// Process the value

Example: To display all elements in the array myList,
for (double value: myList)
System.out.println(value);

⮚ You still have to use an index variable to


• traverse the array in a different order or
• change the elements in the array.
Example: Analyzing Array Elements
■ Objective: The program receives 6 numbers from the user,
finds the largest number and counts the occurrence of the
largest number entered.
Suppose you entered 3, 5, 2, 5, 5, and 5, the largest number is
5 and its occurrence count is 4.

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);

public static void printArray(int[] array) {


for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
Anonymous Array
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}

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: }

typeName… parameterName public static void printMax (double... numbers) {


if (numbers.length == 0) {
■ Only one variable-length parameter System.out.println("No argument passed");
may be specified in a method, and return;
}
this parameter must be the last
parameter. double result = numbers[0];

■ Java treats a variable-length for (int i = 1; i < numbers.length; i++)


parameter as an array. if (numbers[i] > result)
result = numbers[i];

System.out.println(“Max value is " + result);


}
VarargsDemo.java } 30
The Arrays Class (Optional)
■ The java.util.Arrays class contains various static methods for
manipulating arrays:
Method Description
binarySearch Searches an array for a target value - returns the location
of the target if found; if target not found, it returns
–(insertion_point + 1).
The array must be pre-sorted in increasing order.

sort Sorts an array into ascending order of its elements.


equals Checks whether two arrays have the same contents.
fill Fills the whole or part of the array with the specified value.

■ These methods are overloaded for all primitive types.


■ TestArraysClass.java
Two-dimensional Arrays (Optional)
// Declare a two-dimensional array reference variable
dataType[][] refVar;

// Create array and assign its reference to variable


refVar = new dataType[10][10];
// Combine declaration and creation in one statement
dataType[][] refVar = new dataType[10][10];
Creating & Initializing 2D Arrays (Optional)
Create an array called matrix
int[][] matrix = new int[10][10];

Initialize the array with random numbers ranging from 0 to 999.


for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j]=(int)(Math.random()*1000);

33
Lengths of Two-dimensional Arrays (Optional)

int[][] x = new int[3][4];


Lengths of Two-dimensional Arrays (Optional)

int[][] array = { array.length


{1, 2, 3}, array[0].length
{4, 5, 6}, array[1].length
{7, 8, 9}, array[2].length
{10, 11, 12} array[3].length
};

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

You might also like