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

Chapter 07 - Arrays

Chapter 7 covers arrays in programming, explaining that they are collections of values of the same type, with each value referred to as an element. It discusses how to declare arrays, initialize them, and the differences between primitive and reference types, as well as how to manipulate array elements using loops and methods. The chapter also highlights potential errors when working with arrays and provides examples of passing arrays to methods and modifying their contents.

Uploaded by

gj73vc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter 07 - Arrays

Chapter 7 covers arrays in programming, explaining that they are collections of values of the same type, with each value referred to as an element. It discusses how to declare arrays, initialize them, and the differences between primitive and reference types, as well as how to manipulate array elements using loops and methods. The chapter also highlights potential errors when working with arrays and provides examples of passing arrays to methods and modifying their contents.

Uploaded by

gj73vc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Chapter 7 – Arrays

• An array is a collection of values of the same type.


• Each value is known as an element of the array. 0 150
• The index of an element is its position in the list. 1 163
2 158
• c[i] is the element of the array c at index i.
3 160
• The index values start at 0 . index 4 155 element
- c[0] is the 1st element of the array c. 5 161 height[4]
- c[i] is the {i+1}th element of the array. 6 170
• Array index is an integer expression, 7 154
8 168
e.g. 5, i, or 2*k+1.
9 159
• Arrays are objects. A variable of an array type 10 161
stores a reference (address) to the object.
• Arrays can hold both primitive and reference Array height which includes the
type values. heights of a group of people
• The array length is the number of elements
of the array.
Elements of an array are variables
1. The following statement stores a value in an array element.

2. The following statement gets a value from an array element.

Declaring Arrays
• Arrays are objects. A variable of an array type is a reference to the array object.
• Declaring an array involves:
- Declaring a variable reference to the array.
- Reserve the memory space for the array.

There are two equivalent formats to declare a variable, array1, of an int array type.

Multiple variables declared in one statement

To reserve memory space for an array object, use the new keyword. The following statement reserves
space for an array of int type with 10 elements.

The address of the reserved space is assigned to the variable array1.


Array initializers allocate space for the array and instantiate its elements.

This statement:
• Declares a reference, array3, to a double type array and
• Reserves space for 5 double values.
• The address of the memory location allocated to the five values is assigned to the variable
array3.
• The elements of the array are instantiated to values, 8.0, 3.5, 9.17, 2.9, and 6.4.

length is a public constant, a final instance variable, of each array which is set to the number of
items of the array when the array is created.

Example
Output of the program
Printing array a1:
000000000000000

Printing array a2:


0.0 2.0 4.0 6.0 8.0 10.0 12.0 14.0 16.0 18.0

Printing array a3:


12345

Initial Values of Array Elements


When an array is created using the new keyword, elements of the array are assigned default values:
• Numerical primitive type elements are assigned a value 0, and booleans are assigned false.
• Reference type elements, e.g. Strings and objects, are assigned value null.

Using for Loop to Initialize Array Elements


The following code demonstrates how to use the control variable of a for-loop to initialize array
elements.
• An array of 10 integer elements is created and its elements are assigned values 0, ..., 18.
• A constant, ARRAY_LENGTH, is declared to store the array length.
Sum of an Array Elements
To add up elements of an array
• Create a variable total and initialize it to 0.
• Use a for statement to loop through all the array elements. In each iteration of the loop, add
the value of the array element, a[i], to total.

Be aware of the following errors when using arrays:


• Accessing an element outside the index range [0 - array.length-1] will result in a run-
time error condition (ArrayIndexOutOfBoundsException).
• Off-by-One error occurs when missing to process one item, at the beginning or end of the array.

Calculating the Frequency of Elements of an Array


Assume data is an array which stores data values. The possible data values are 1, ..., n, for an
integer n.

A frequency array for these data summaries the number of times each of the data element occurs in the
array data.

For example, if
• the possible data values are 1, ..., 5
• the array data is {3,2,5,1,3,2,2,1,3,2,1,3,3}
The following table shows the frequency of each element

Element 1 2 3 4 5
Occurrences 3 4 5 0 1

The following array represents the frequency for the corresponding index.
index 0 1 2 3 4 5
frequency Array: { 0, 3, 4, 5, 0, 1}

As index 0 has no corresponding data value, hence the frequency of data item 0 is 0.
Example
A survey of the quality of a product was conducted among a group of the product users. Each user must
assign a rating from 1 to 10. The responses to this survey were stored in an array, data. To analyze the
result of the survey:

1. Create an array frequency with dimension 11. The element frequency[i] will represent
the number of i responses. For example, frequency[1] will represent the number of
times a response 1 is repeated.
2. The first element of this array, frequency[0], will be ignored since 0 is not a valid rating.
3. Loop through the elements of data array, and for each item, increase the corresponding
counter, frequency[item].

Rating Frequency of Rating


1 1
2 4
3 1
4 2
5 3
6 3
7 2
8 4
9 3
10 0
Types of Variables
There are two types of variables in Java:
• Primitive type variables: The variable name is associated with a location of the memory which contains
a value. Primitive types include boolean, char, byte, short, int, long, float and
double.
• Reference type variables: These variables refer to objects.
- A reference variable is associated with a memory location that contains the “address” where the
object is stored in the memory.
- Examples of reference variables: variables referring to arrays or objects of any class.

The Enhanced for Loop


The for-loop is convenient for processing arrays as shown by the examples above.

The enhanced for loop provides a short hand that expresses that for-loop in a condensed format. In
the following example, arr is a double array.

for-loop code Equivalent enhanced for-loop code

Caution

The variable val in the enhanced for-loop header assumes values of the elements of the array arr not
the indexes of the array.
To express the two fragments of code in a parallel fashion, write the code for the standard for-loop
above as:

for-loop code
Limitations of the Enhanced for-Loop
As the enhanced for loop refers to elements using some local variable such as the variable value
above, programmers using the enhanced for-loop has no direct access to the actual elements, or even
the indices of the array, and hence cannot modify elements of the array.

References and Reference Parameters


In programming languages in general, there are two mechanisms for calling methods:
• Call-by-value: The expression passed as an argument to the method call is evaluated. The resulting
value is assigned to the formal parameter, and then the body of the method is executed. This
technique is used in Java
• Call-by-reference: The body of the method is executed, where all references to the parameter will
access the actual parameter and can modify it. This technique is NOT used in Java.

However when the value passed to a method is a reference (i.e. an address of a memory location)
then the referenced object can be modified by calling the method, thereby achieving the benefits of
call-by-reference.

Passing Arrays to Methods


• An array variable is a reference which contains the address where the actual elements of the array
reside in the memory.
• A method with an array parameter can modify the elements of the array.
• A method with an array parameter must be declared with the appropriate type.

• To call the method, pass only the array name as the argument and do not include brackets or
indices. For example, in the following call, the argument a is a variable referring to an array of int
type:

While the following call incorrect


Example:
The following method takes as an argument an int array and it will double the value of each element of
the array.

Printing array a:
12345
Array a after calling doubleElements:
2 4 6 8 10
Passing Array Elements to a Method
The following program demonstrates that passing primitive type array elements as arguments to
method. The argument can’t be modified by calling the method.

Printing array a:
12345
Printing array after calling doubleInt:
12345
Arrays of Objects
While in previous examples, array elements have primitive types, we will introduce arrays of objects of
any class. For example, a car racing application may maintain the collection of all cars in an array. The
following example demonstrates how to create an array of Car objects and invoke methods from that
collection, where a car has attributes speed, maker and color. The program will allow the user to
change the speed of the cars and determine the average speed of all cars in the collection.
Aliases
Semantics (meaning) of the assignment statement for primitive type variables:
int n1 = 5;
int n2 = 12;

n1 5 12 n2

n1 = n2;

n1 12 12 n2

The value in the variable n2 is copied to the variable n1.


System.out.print(n1);
Will display 12.

n1 = 99;
System.out.print(n2);

Will display 12, as changing the value of n1 does not affect the value of n2.
Semantics of assignment statement for reference type:
The following class Num represents numbers as objects.

To demonstrate the semantics of reference type variable we will create two references to objects of type
Num and assign one reference to the other reference.

Num num1 = new Num(7);


Num num2 = new Num(15);

num1 value 7

num2 value 15

num1 = num2;

num1
value 7

num2 value
value 15
System.out.println("num1 value: " + num1.toString( ));
Will display 15.
Set value of num1 to 100, and then display the value of num2.
num1.setValue(100);
System.out.println("num 2 value: " + num2.toString( ));

What value will be displayed?


Aliases are variables containing the same address and hence they refer to the same object. num1 and num2 are
aliases since they both refer to the same object. Changing the object using one of the aliases will be reflected on the
other alias.

Passing Variables to Methods


Java passes variable to methods by value. The value of a variable passed as an argument to a method is
evaluated the assigned to the formal parameter of a method. The body of the method is executed after
the value the formal parameter is assigned to the value of the actual parameter.
That means methods have no access to the variable passed to it, only it has its value.

Passing Primitive Type Parameters


When passing a primitive type variable as an argument to a method call, the value of the argument is
assigned to the formal parameter. Changes to the formal parameter within the body of the method do
not affect the argument as these two variables are two different primitive variables.

This program demonstrates a logical error, where a method is created to change the value of a primitive
variable.
Passing Reference Type Parameters
1. Can a method change the value of reference type variable that it receives as a parameter?

2. If a method is called with reference type parameter, could it change the object that the parameter is
referring to?

Question:
1. Can you change a primitive type variable by passing it as an argument to a method?
2. Can you change a reference type variable to a different reference value by passing it as a
parameter to a method?
3. Can you change the object a reference type variable referring to by passing this variable as a
parameter to a method?
Note
When passing a reference type variable as an argument to a method, the value of the reference is
assigned to the formal parameter before executing the body of the method. The formal parameter
and the actual parameter are now aliases. Changes to the object done through the formal
parameter will be reflected on the object referred to by the actual parameter
Arrays as Parameters

Revision of the Array Concept


The following code creates an array with 3 elements of type int. The call new int[3] will create an
array that can store 3 elements of type int and instantiate these elements to the default value 0. The
new call will return the address of that object in the memory. The assignment will save this address in
the variable a.
int [] a = new int[3];

Array object
Array reference
Address:98975 index Element
0 0
a 98975 1 0
2 0

Note that the arrow represents that the variable a contains the address of the object at memory
location pointed by the arrow (memory location 98975).

Exercise
In this exercise we will investigate the difference between passing a primitive-type and reference type
parameters to a method. Note that an array is an object and hence a variable of an array type is a
reference or address of the actual array object.
1. Define a method, increment, which takes an integer-type parameter and doesn’t return any
value. The purpose of this method is to increment the value of the parameter.
a. Define the method increment.
b. Write a test program where you declare an int variable num, instantiate this variable and call
the method increment passing to it this variable in order to increment num. Print the value of
the variable num after calling increment.
c. Did the value of num increased or not?
d. Pass to the method an element of an int array and observe if that element will increment.

2. Define a method, incrementArray. This method will take as a parameter an array of int and
does not return any value. Define the method so that it will loop through the elements of the
parameter array and increment each element of the array by 1.
a. Define the method incrementArray.
b. Write a test program to
i. Create an array, numbers, and use array initialization to initialize the elements of the array
to {8, -5, 17, 4, 9, 12}.
ii. Call the method increaseArray passing to it the array numbers. Do not index the array;
only the reference (the name of the array) should be passed.
iii. Print the elements of the array.
c. Did the values of the elements of the array, numbers, increased or not?

3. Define a method reassignArray. This method takes an array of int as a parameter. It creates
an array of the same type and assigns the parameter to this array.
a. Define the method reassignArray. The method will reassign its parameter to an array
{0, 0, 0, 0, 0}.
b. Write a test program to
i. Declare and instantiate an array a which includes the elements 3, 7, 4, 8, 2.
ii. Call the method reassignArray passing to it the array a.
iii. Print out the elements of the array a.
c. Did the method reassignArray succeed in reassigning the array a to the array {0, 0, 0,
0, 0})?
4. From your answers to questions 1, 2, and 3, what would you conclude about the ability of a method
to change
a. A parameter of primitive types?
b. A parameter of reference type such as an array?
c. The elements referenced by a parameter which is an array?

Passing Primitive Types vs. Passing Reference Type Arguments


1) Methods CAN NOT modify primitive type variables passed as arguments.
2) Methods CAN NOT change the value of a reference type variable passed to the method as an
argument.
3) Methods CAN modify the object referred to by a reference variable which is passed as an
argument to the method.

You might also like