The following code fragment is designed to print the elements of an
array of integers arr
backwards (from the end of the array to the
beginning), each on its own line:
for (int i = 0; i < arr.length; i++) { System.out.println(arr[arr.length - i]); }
However, this code produces a runtime error. Identify what kind of runtime error is produced, on which line the bug is coming from, and what could be done to fix it.
Recall from today’s lecture that an array is a collection of data values of the same type. Like strings, each element of an array has an index, and the first element of any array has an index of 0.
In fact, the String
class specifies that each String
object
keep an array of char
s. For any and every String
in a Java
program, this internal array is what stores the actual characters
that make up the string. (This is why String
indexing is the
same as arrays — methods like charAt()
from the String
class
merely access the char
array stored in the string, using the
index provided as a parameter.)
Unlike String
s, however, arrays are mutable — any element
can be changed after the array is created. But there is one
drawback: when an array of a certain size is created, it cannot
be made larger or smaller. Therefore, in order to have enough
space in the array, the number of elements in the array must be
known before the array is created.
Arrays are the first of several examples of collections you will see in this course. Collections become especially relevant after unit 5, since arrays can be thought of as the simplest data structure.
There are many situations where using an array is natural. There are many more situations where using an array is necessary (e.g., keeping track of students’ grades, sports scores, quantities of ingredients in a recipe, et cetera).
What are two different ways we can use a single line of Java
code to declare and create a new array called arr
that can
hold five integers, where all five integers in the array are
initially set to 0? 1
What expression will give us access to the third element in the array from the previous question (the “third” element in terms of English ordinals, not by index). 2
What expression will give us access to the last element in the array from the previous question? 3
Provide an assignment statement that will double the value of the second element in the array declared in the previous question. 4
What are the two pictures we should draw to represent what happens in memory when the following two code snippets are executed? What is the difference between them? 5
// snippet A int[] a1 = {1, 2, 3, 4}; int[] a2 = a1; // snippet B int[] b1 = {1, 2, 3, 4}; int[] b2 = {1, 2, 3, 4};
Given the two snippets above, what is the value of the
expression a1 == a2
? 6
Given the two snippets above, what is the value of the
expression b1 == b2
? 7
Fill in the blanks of the method below to create a method that
raises each element in an array of integers to some power.
For example, power(a1, 3)
, where a1
refers to the array
in code snippet A above, should cube each element in a1
,
so that a1
now has the elements {1, 8, 27, 64}
.
Hint: you can use the method Math.pow(double a, double b)
which returns the result of raising a
to the power of b
and returns a double
. 8
public static void power(______, ______) { for (______; ______; ______) { ____________; } }
The manager of the Boston Bruins hockey team has asked us to write a program that will analyze the team’s results. As your solution to each part, write a single Java method that takes any necessary arrays or integers as parameters and returns the results, unless otherwise stated.
A method called gameResults
that takes two integer arrays as parameters:
one containing the goals scored by the Bruins in each of a series of games,
and one containing the goals scored by their opponents in those same games.
It should also take an integer that will specify the game for which the
user would like the results. The method will return a string: either
"Win"
, "Loss"
, or "Tie"
. 9
A method called printScores
that takes two integer arrays as
parameters. It prints all of the Bruins scores on one line, separated by
spaces. Then prints all of the opponents scores on the next line, also
separated by spaces. 10
A method called anyTieGames
that takes two integer arrays as parameters:
one containing the goals scored by the Bruins in each of a series of games,
and one containing the goals scored by their opponents in those same games. For
example, to represent a series of games in which the Bruins lost 1-2, won 4-1,
and tied 3-3, we would pass in the following arrays:
int[] bruinsGoals = {1, 4, 3}; int[] opponentsGoals = {2, 1, 3};
The method should return true
if there is at least one tie game in the
results, and false
if there are no tie games in the results.
You may assume that the two arrays passed in to the method
have the same length. 11
A method called determineRecord
that takes the same types of parameters
as anyTieGames
, but that computes and returns the Bruins record. The record
should be returned as an array of three integers, in which the first element is
the number of wins, the second element is the number of losses, and the third
element is the number of ties. Note that your method will need to create the
array that it returns, and then use it to store cumulative counts of the number
of wins, losses, and ties. 12
A method called findScore
that takes as parameters an integer array of
scores and a single integer score s
, and returns the index of the first
occurrence of s
in the array of scores, or -1 if s
does not appear in the
array. 13
A method called avgScores
that takes a parameter of an integer
array of scores, and returns the average of those scores. 14
You can use the new
operator and specify the length; Java
automatically fills each element with the value 0.
int[] arr = new int[5];
Or, you can write an initialization list.
int[] arr = {0, 0, 0, 0, 0};
arr[2]
↩
arr[arr.length - 1]
↩
arr[1] = arr[1] * 2
↩
Here’s the picture we’d draw for snippet A:
And here’s the picture for snippet B:
In addition, see
Addresses.java
for a
program that shows the difference in memory addresses between
two arrays created at different times. The program shows examples
of assignment statements like the snippet above. ↩
true
, since the references in both variables refer to the
same array. In other words, since the reference is the value of
the variable, and the values of both variables are the same,
we get true
. This use of ==
is precisely the same as
when comparing two integer variables that have the same value. ↩
false
, since two different arrays have been created with
their own positions in memory. Since the value of the variable
is the reference, and both variables reference a different
array, the references are not the same. ↩
There are several approaches here, but the main idea is that we
need a looping structure to raise each element of the array
to the specified power. (The other detail is that Math.pow()
returns a double, which we can simply cast to int
.)
public static void power(int[] arr, int p) { for (int i = 0; i < arr.length; i++) { arr[i] = (int)Math.pow(arr[i], p); } }
Notice that we aren’t returning anything here. Unlike String
s,
arrays are mutable, which means we can alter their elements
directly. Furthermore, since any int[]
variable is a reference,
we can pass in a reference to any array and change the array
directly, without having to return a new array. ↩
Here’s one possible implementation:
/* * Given two arrays of the same length representing the scores * of the Bruins and another team in games they played against * each other, and an array index specifying the game we are * interested in, return the string "Win" if the Bruins won * game i, "Loss" if the Bruins lost game i, or "Tie" if they * tied. */ public static String gameResults(int[] bruins, int[] other, int i) { if (bruins[i] < other[i]) { return "Loss"; } else if (bruins[i] > other[i]) { return "Win"; } else { return "Tie"; } }
Here’s one possible implementation:
/* * Given two arrays of the same length representing the scores * of the Bruins and another team in games they played against * each other, print the scores of the Bruins on one line, * separated by spaces, then the scores of the other team * on the next line, separated by spaces. */ public static void printScores(int[] bruins, int[] other) { for (int i = 0; i < bruins.length; i++) { System.out.print(bruins[i] + " "); } System.out.println(); for (int i = 0; i < other.length; i++) { System.out.print(other[i] + " "); } System.out.println(); }
Here’s one possible implementation:
public static boolean anyTieGames(int[] bruins, int[] other) { for (int i = 0; i < bruins.length; i++) { if (bruins[i] == other[i]) { return true; } } return false; }
Here’s one possible implementation:
public static int[] determineRecord(int[] bruins, int[] other) { int wins = 0; int losses = 0; int ties = 0; // note: we are assuming that bruins.length == other.length! for (int i = 0; i < bruins.length; i++) { if (bruins[i] > other[i]) { wins++; } else if (bruins[i] < other[i]) { losses++; } else { ties++; } } int[] record = {wins, losses, ties}; return record; }
Here’s one possible implementation:
public static int findScore(int[] bruins, int s) { for (int i = 0; i < bruins.length; i++) { if (bruins[i] == s) { return i; } } return -1; }
Here’s one possible implementation:
public static double avgScores(int[] bruins) { double sum = 0; for (int i = 0; i < bruins.length; i++) { sum += bruins[i]; } return sum/bruins.length; }
Last updated on July 7, 2025.