Unit 3

Arrays and Algorithms

Solutions & CommentaryUnit 3 MC Practice Test

Open a question, then select an answer choice to see whether it’s correct and why.

Question 13.6 Array Algorithms & Nested Loops

Consider an integer array nums, which has been properly declared and initialized with one or more integer values. Which of the following code segments counts the number of even values found in nums and stores the count in evenCount?

A
int evenCount = 0;
for (int i = 0; i < nums.length; i++) {
  if (i % 2 == 0) {
    evenCount++;
  }
}

Incorrect

This tests i, the index, instead of nums[i], the element. It counts how many indexes are even, no matter what values the array holds.

B
int evenCount = 0;
for (int i = 0; i <= nums.length; i++) {
  if (nums[i] % 2 == 0) {
    evenCount++;
  }
}

Incorrect

The condition i <= nums.length allows one pass too many. On the last pass i equals nums.length, so nums[i] throws an ArrayIndexOutOfBoundsException.

C
int evenCount = 0;
for (int i = 0; i < nums.length; i++) {
  if (nums[i] % 2 == 0) {
    evenCount++;
  }
}

Correct

evenCount starts at 0 before the loop, the loop visits every valid index, and the count goes up each time the element nums[i] is even.

D
for (int i = 0; i < nums.length; i++) {
  int evenCount = 0;
  if (nums[i] % 2 == 0) {
    evenCount++;
  }
}

Incorrect

evenCount is declared inside the loop, so it's reset to 0 on every pass and never builds up a total. It also doesn't exist after the loop ends, so the count isn't stored anywhere.

Question 23.1 One-Dimensional (1D) Arrays

What is the output of the following code segment?

double[] numArray = new double[18];
numArray[0] = 2.2;
System.out.print(numArray[6]);
A

0

Incorrect

0 is the default value for an int array. This is a double array, and a double prints with a decimal point.

B

0.0

Correct

new double[18] sets every element to the default value 0.0. Only index 0 is changed, so numArray[6] still holds 0.0.

C

2.2

Incorrect

2.2 is stored at index 0. The print statement uses index 6, which was never assigned.

D

null

Incorrect

null is the default for arrays of objects, such as String[]. A double is a primitive, so its default is 0.0.

Question 33.1 One-Dimensional (1D) Arrays

What is stored in sum after the code segment below is run?

int[] values = {10, 7, 3, 4, 9, 2, 1};
int sum = values[3] + values[4];
values[0] = sum;
sum += values[0];
A

13

Incorrect

That's the value of sum after the second line, 4 + 9. The last line then adds values[0] to it.

B

14

Incorrect

This counts positions starting at 1, which gives 3 + 4. Indexes start at 0, so values[3] is 4 and values[4] is 9.

C

23

Incorrect

This adds the original values[0], which was 10. The third line replaces values[0] with 13 before the last line uses it.

D

26

Correct

values[3] is 4 and values[4] is 9, so sum is 13. Then values[0] becomes 13, and the last line adds it to sum: 13 + 13.

Question 43.2 For Loops

Which of the following code segments will produce the same output as the code segment below?

for (int j = 5; j < 21; j += 5) {
  System.out.print(j);
}
A
for (int j = 1; j <= 4; j++) {
  System.out.print(j * 5);
}

Correct

The original prints 5, 10, 15, and 20. Here j is 1, 2, 3, and 4, and j * 5 gives those same four values.

B
for (int j = 0; j < 20; j += 5) {
  System.out.print(j);
}

Incorrect

This starts at 0 and stops before 20, so it prints 0, 5, 10, and 15. Every value is 5 too low.

C
for (int j = 5; j <= 25; j += 5) {
  System.out.print(j);
}

Incorrect

The condition j <= 25 lets 25 in, so this prints one extra value. The original stops after 20.

D
for (int j = 1; j < 4; j++) {
  System.out.print(j * 5);
}

Incorrect

With j < 4, j only reaches 3, so this prints 5, 10, and 15. It's missing 20.

Question 53.3 1D Array Traversals

Consider the following method.

public void divideByTwo(int[] array) {
  for (int j = 0; j < array.length; j++) {
    array[j] = array[j] / 2;
    System.out.println(array[j]);
  }
}

Which of the following can be used to replace the body of the method so that array will contain the same values?

A
for (int n : array) {
  n = n / 2;
  System.out.println(n);
}

Incorrect

This is a limitation of the enhanced for loop: its variable n holds a copy of each element, and the loop gives you no index. Assigning to n changes only the copy, so this prints the halved values but array itself is never changed. Storing a new value in an array takes an index, as in array[j] = ....

B
for (int j = 1; j <= array.length; j++) {
  array[j] = array[j] / 2;
  System.out.println(array[j]);
}

Incorrect

Starting at 1 skips the first element, and j <= array.length makes the last pass use array[array.length], which throws an ArrayIndexOutOfBoundsException.

C
int j = 0;
while (j < array.length) {
  array[j] = array[j] / 2;
  System.out.println(array[j]);
  j++;
}

Correct

This is the same loop written as a while loop. The initialization, condition, and update are identical, so every element is halved exactly as before. Because it has the index j, it can assign to array[j], which an enhanced for loop can't do.

D
for (int j = array.length - 1; j > 0; j--) {
  array[j] = array[j] / 2;
  System.out.println(array[j]);
}

Incorrect

The condition j > 0 stops before index 0, so the first element is never halved. A backward traversal needs j >= 0 to reach it.

Question 63.5 Enhanced For Loops

What is printed as a result of executing the code segment below?

int[] arr = {10, 8, 14, 12, 6};

for (int j : arr) {
  j = j + 5;
  System.out.print(j + " ");
}

for (int j : arr) {
  System.out.print(j + " ");
}
A

15 13 19 17 11 10 8 14 12 6

Correct

In an enhanced for loop, the variable j is a copy of each element, not the element itself. The first loop adds 5 to each copy and prints it. An enhanced for loop can't change the values stored in an array, so arr is untouched and the second loop prints the original values.

B

15 13 19 17 11 15 13 19 17 11

Incorrect

This would be right if the first loop changed the array, but an enhanced for loop can't do that. j = j + 5 changes only j, a copy of the element, so the second loop still sees the original values. Changing the array would take an indexed loop with arr[i] = arr[i] + 5.

C

10 8 14 12 6 10 8 14 12 6

Incorrect

It's true that the enhanced for loop leaves the array unchanged. But the copy j is still an ordinary variable that can be changed and used inside the loop, and the first loop prints j after adding 5 to it. So the first five values printed are the increased copies.

D

10 8 14 12 6 15 13 19 17 11

Incorrect

This has the two halves backward. The first loop prints each copy j after 5 is added to it. Since changing the copy never changes the array, the second loop prints the original values, not the increased ones.

Question 73.6 Array Algorithms & Nested Loops

What is output by the following code?

int total = 0;
for (int i = 1; i <= 5; i++) {
  for (int j = 1; j <= i; j++) {
    total = total + j;
  }
}
System.out.println(total);
A

15

Incorrect

That's 1 + 2 + 3 + 4 + 5, which is what the inner loop adds on the last pass of the outer loop alone. The earlier passes add to total too.

B

25

Incorrect

The inner loop doesn't run 5 times on every pass. It runs i times, and it adds j, which changes on each pass.

C

35

Correct

The inner loop adds 1 through i on each pass of the outer loop. That adds 1, then 3, then 6, then 10, then 15, for a total of 35.

D

55

Incorrect

That would be the result if the inner loop added i each time. It adds j, which counts from 1 up to i.

Question 83.6 Array Algorithms & Nested Loops

Consider the following method, which is intended to return an array of Strings that contains the elements of the parameter words arranged in reverse order. For example, if words contains {"Ken", "Isaiah", "Jose", "Esosa"}, then a new array containing {"Esosa", "Jose", "Isaiah", "Ken"} should be returned and the parameter words should be left unchanged.

public String[] reverseArray(String[] words) {
  String[] reversedArray = new String[words.length];
  for (int i = 0; i < words.length; i++) {
    /* missing statement */
  }
  return reversedArray;
}

Which code segment should replace /* missing statement */?

A
reversedArray[i] = words[words.length - i];

Incorrect

On the first pass i is 0, so this uses words[words.length], which is out of bounds. The last element is at words.length - 1.

B
reversedArray[words.length - i] = words[i];

Incorrect

On the first pass i is 0, so this assigns to reversedArray[words.length], which is out of bounds.

C
words[i] = reversedArray[words.length - 1 - i];

Incorrect

The assignment goes the wrong way. It overwrites words, which is supposed to stay unchanged, with elements of reversedArray, which are all still null.

D
reversedArray[i] = words[words.length - 1 - i];

Correct

When i is 0, this copies the last element of words, at index words.length - 1. As i goes up, the index into words goes down, and words itself is never modified.

Question 93.3 1D Array Traversals

In the following code segment, assume that double testScore has been properly declared and initialized. The code segment is intended to print the number of times testScore appears in array testScores.

double[] testScores = {75.5, 78.0, 70.2, 72.5, 73.5, 70.0, 68.0, 71.5, 75.3};
int count = 0;
for (int i = 0; i <= testScores.length; i++) {
  if (testScores[i] == testScore) {
    count++;
  }
}

The code segment does not work as intended. Which of the following changes should be made so the code segment works correctly?

A

Change int count = 0; to int count = 1;

Incorrect

A count has to start at 0. Starting at 1 makes the result one too high, and the loop still goes out of bounds.

B

Change i <= testScores.length to i < testScores.length

Correct

With <=, the last pass uses testScores[testScores.length], which throws an ArrayIndexOutOfBoundsException. The last valid index is length - 1, so the condition must be <.

C

Change testScores[i] == testScore to testScores[i] = testScore

Incorrect

A single = is assignment, not comparison. It doesn't produce a boolean, so the if statement won't compile.

D

Change int i = 0 to int i = 1

Incorrect

This skips the first element, and the loop still goes out of bounds on its last pass.

Question 103.2 For Loops

How many times does the body of the for loop below execute?

for (int a = 0; a < 12; a = a + 5) {
  System.out.println(a + " ");
}
A

2

Incorrect

a is 0, then 5, then 10, and 10 < 12 is still true. That's a third pass.

B

3

Correct

a takes the values 0, 5, and 10 while the condition is true. Then a becomes 15, which fails a < 12.

C

4

Incorrect

After the pass where a is 10, the update makes a equal to 15. The condition 15 < 12 is false, so there's no fourth pass.

D

12

Incorrect

That would be the count if the update were a++. Here a goes up by 5 on each pass.

Question 113.6 Array Algorithms & Nested Loops

The method countOdds below is intended to return the number of times an odd number appears in the array myArray. The method may not work as intended.

public int countOdds(int[] myArray) {
  int count = 0;
  for (int j = 0; j < myArray.length; j++) {   // Line 4
    if (myArray[j] % 2 != 0) {
      count++;
    }
  }

  return count;
}

Which of the following changes, if any, can be made to Line 4 so that the method will work as intended?

A
for (int j = 0; j <= myArray.length; j++) {

Incorrect

The method already works, and this change breaks it. With <=, the last pass uses myArray[myArray.length], which is out of bounds.

B
for (int j = 1; j < myArray.length; j++) {

Incorrect

The method already works, and this change breaks it. Starting at 1 skips the first element, so an odd number at index 0 is never counted.

C
for (int j = 0; j < myArray.length - 1; j++) {

Incorrect

The method already works, and this change breaks it. Stopping at length - 1 skips the last element.

D

No change is needed; the method already works as intended.

Correct

The loop visits every index from 0 through length - 1, and % 2 != 0 is the right test for odd numbers, including negative ones. count starts at 0 and is returned after the loop.

Question 123.3 1D Array Traversals

Given the following array myNewArray and the method addThree(), what will the values of myNewArray be after addThree() is executed?

private int[] myNewArray = {-5, 2, 8, 10, 17};

public void addThree() {
  for (int i = 0; i < myNewArray.length; i = i + 2) {
    myNewArray[i] = myNewArray[i] + 3;
  }
}
A

{-2, 2, 11, 10, 20}

Correct

i is 0, 2, and 4, so 3 is added to the elements at those indexes: -5, 8, and 17. The elements at indexes 1 and 3 are skipped.

B

{-2, 5, 11, 13, 20}

Incorrect

That adds 3 to every element, which is what i++ would do. The update is i = i + 2, so only every other element changes.

C

{-5, 5, 8, 13, 17}

Incorrect

That changes the elements at indexes 1 and 3. The loop starts at 0, so it changes indexes 0, 2, and 4.

D

{-2, 2, 11, 10, 17}

Incorrect

This misses the last element. When i is 4, the condition 4 < 5 is true, so index 4 is changed too.

Question 133.3 1D Array Traversals

What is printed to the console based on the code below?

String[] pets = {"cat", "puppy", "hippo", "rabbit", "kangaroo"};
for (int i = pets.length - 1; i >= 0; i--) {
  System.out.print(pets[i] + " ");
}
A

cat puppy hippo rabbit kangaroo

Incorrect

That's the array in its original order. This loop starts at the last index and counts down, so it prints backward.

B

kangaroo rabbit hippo puppy

Incorrect

This leaves out cat. The condition is i >= 0, so the loop does run for index 0.

C

kangaroo rabbit hippo puppy cat

Correct

The loop starts at the last index, pets.length - 1, and counts down through index 0, printing every element in reverse order.

D

rabbit hippo puppy cat

Incorrect

This leaves out kangaroo. The loop starts at pets.length - 1, which is index 4, the last element.

Test prepUnit 3 FRQ Test — what to study

The format. This FRQ is different from Units 1 and 2. You won't write a whole class. The class is already written for you: its header, a 1D array instance variable, and its constructor. You write two methods inside it, part (a) and part (b), and each one traverses the array.

You may use your own handwritten notes, but the scoring guidelines aren't shown until after the test. Nothing on the test will remind you what earns points.

The scoring. The test is worth 10 points, 5 for each part. Each point is a separate thing the scoring guidelines look for, so a method that's mostly right still earns most of its points. Attempt both parts, even if part (a) didn't go well.

Things to Keep in Mind

  • The types of methods you'll have to write are included in the Array Algorithms & Nested Loops section on this page. It could be helpful to include these algorithms in your handwritten notes.
  • You only have to write the body of each method. You do not need to write the method signatures.
  • The method you create in part (a) will need to be used in part (b).
  • Even if your method contains errors, you may still earn points by returning a value with the correct data type, writing your loop header correctly for your traversal, and/or correctly declaring and initializing a variable if needed.

How to practice

  • Complete the Unit 3 FRQ Practice Test in Schoology. This practice test has the same format as the actual test.
  • Complete the Library and Team practice FRQs in AP Classroom. Use the AI Tutor to check your work.
  • Ask the tutor for a fresh practice prompt to practice for the Unit 3 FRQ Test, or to check/grade individual methods you wrote for practice FRQs.

Select a topic to expand it.

3.1One-Dimensional (1D) Arrays

A data set is a collection of related pieces of information organized together so you can analyze it, answer questions, or solve problems. Each single item in it is a value.

Programs answer questions about data sets — what's the largest? what's the average? how many are over 100? — by processing the values one at a time. To do that, the program first needs somewhere to keep all of them.

What a 1D array is

A data structure is a structure for organizing, processing, retrieving, and storing data. It contains zero or more elements — an element is a single value or object in a data structure.

A one-dimensional (1D) array is a data structure that holds multiple values of the same type.

Index01234
Element"Java""Python""C++""Swift""Kotlin"

Instead of five separate variables (lang1, lang2, …), you get one named array holding all five. An array can hold primitive values (int, double, boolean) or object references (String, Painter, …).

Giving a whole collection of data one name is called data abstraction — it lets you think about what the data means instead of how each piece is stored.

Declaring and creating an array with new

Declare it: the element type, square brackets, and a name.

int[] scores;

Create it with the new keyword, the element type, and how many elements it will hold:

scores = new int[5];

Or do both in one line:

int[] scores = new int[5];

Default values

An array created with new is not empty — every element is automatically set to the default value for its type. These are the same defaults instance variables get.

DeclarationEvery element starts as
int[] numbers = new int[5];0
double[] numbers = new double[5];0.0
boolean[] status = new boolean[5];false
String[] names = new String[5];null

A String is an object, and null is the default for any object reference — it means "this element doesn't refer to any object yet." Creating an array of objects does not create any objects. new String[5] makes five empty slots, not five strings.

Creating an array with an initializer list

When you already know the values, use an initializer list — a comma-separated list of values inside curly braces { }:

int[] scores = {75, 90, 83, 78, 97};
String[] flavors = {"chocolate", "vanilla", "strawberry"};

Java counts the values and sizes the array to fit. There's no new and no size in the brackets.

Indexes

An index is an integer that indicates the position of a value in a data structure. Array indexes start at 0.

int[] scores = {75, 90, 83, 78, 97};
Index01234
scores7590837897

The first element is at index 0, and the last element is at index length - 1 — here, index 4.

Length

The length of an array is how many elements it can store. Get it with the array's name, a dot, and length:

int[] scores = new int[5];
System.out.println(scores.length);
5

length has no parentheses. It's an attribute of the array, not a method: scores.length, never scores.length().

An array's size is fixed. Once it's created, it can't grow or shrink, and its element type can't change. You can change the values stored in it — you just can't change how many there are.

Accessing and modifying elements

Square brackets with an index access one element. Put that on the left of = to modify it, exactly like assigning to a variable:

int[] scores = {75, 90, 83};
scores[0] = 85;
scores[1] = 95;
scores[2] = 90;

System.out.println(scores[1]);
95

You can use an element anywhere you could use a variable of that type:

int total = scores[0] + scores[2];   // 175
scores[2] += 5;                      // scores[2] is now 95

ArrayIndexOutOfBoundsException

The valid indexes are 0 through length - 1. Using any other index — negative, or length or greater — throws an ArrayIndexOutOfBoundsException while the program runs.

int[] scores = {75, 90, 83};
scores[3] = 94;   // ERROR — the indexes are 0, 1, and 2
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

The most common array mistake on tests: using length as an index. scores[scores.length] is always out of bounds. The last element is scores[scores.length - 1].

Arrays are objects

An array is an object, and an array variable is a reference variable — it holds the array's location in memory, not the elements themselves. You'll see why that matters when an array is passed to a method or stored as an instance variable: both names point to the same array, so a change made through one shows up through the other.

Using data responsibly

Before writing code that analyzes a data set, it's worth asking whether the data deserves to be trusted. A program can only be as good as the data it runs on.

  • Privacy. When a program collects and stores personal data, users' privacy is at risk. Programmers should try to protect it.
  • Data quality. Some data sets are incomplete or contain inaccurate data. A program built on bad data can work incorrectly, even when the code itself is right.
  • The right data for the question. A data set collected for one question may not give correct answers for a different one. Survey results from one school, for example, can't tell you about every student in the country.
  • Algorithmic bias is systemic and repeated errors in a program that create unfair outcomes for a specific group of users. It often comes from how the data was collected — if a group was left out or underrepresented, the program's results can be unfair to them.
3.2For Loops

A for loop is an iteration statement, like a while loop, that packs everything that controls the loop into one line.

for (int count = 0; count < 5; count++) {
  System.out.println(count);
}
0
1
2
3
4

The three parts of a for loop header

for (int count = 0; count < 5; count++)
PartExampleWhat it does
Initializationint count = 0Declares and initializes the loop control variable
Conditioncount < 5A boolean expression — the loop keeps running while it's true
Updatecount++Changes the loop control variable after each pass

A loop control variable is a variable that is changed by a constant value and determines when the loop ends.

The three parts are separated by semicolons, not commas.

The order things happen in

This order is what every tracing question tests:

  1. Initialization runs once, before anything else.
  2. The condition is checked. If it's false, the loop ends right away.
  3. The body runs.
  4. The update runs.
  5. Back to step 2.

The update happens after the body, and the condition is checked after the update. If the condition is false the very first time, the body never runs at all.

Increment and decrement

Java has shortcut operators for changing a value by 1:

OperatorNameSame as
number++increment — increase by 1number += 1
number--decrement — decrease by 1number -= 1

The update doesn't have to be ++. Any change works:

for (int i = 0; i < 20; i += 5)     // 0, 5, 10, 15
for (int i = 10; i > 0; i -= 3)     // 10, 7, 4, 1

Tracing a for loop

Keep a table with one row per check of the condition:

for (int number = 3; number > 0; number--) {
  System.out.println(number * 5);
}
numbernumber > 0Output
3true15
2true10
1true5
0false(loop ends)

The condition was checked 4 times, but the body ran 3 times.

Counting how many times a loop runs

Tests often ask how many times a loop body executes. List the values the loop control variable takes while the condition is still true:

for (int a = 0; a < 12; a = a + 5) {
  System.out.print(a + " ");
}

a is 0, 5, 10 — then 15, which fails a < 12. The body runs 3 times and prints 0 5 10 .

For the common shape that adds 1 each time:

Loop headerRuns
for (int i = 0; i < n; i++)n times
for (int i = 1; i <= n; i++)n times
for (int i = 1; i < n; i++)n - 1 times
for (int i = 0; i <= n; i++)n + 1 times

Off-by-one errors

An off-by-one error happens when a loop repeats one time too many or one time too few. This loop is supposed to print 1 through 10:

for (int count = 1; count <= 11; count++) {
  System.out.print(count + " ");
}
1 2 3 4 5 6 7 8 9 10 11

The condition count <= 11 lets 11 in. Either fix works:

for (int count = 1; count <= 10; count++)
for (int count = 1; count < 11; count++)

When a loop's output is almost right, check the condition first: < versus <=, and the starting value. That's where off-by-one errors live.

for loops and while loops

Every for loop can be rewritten as a while loop, and the other way around. The same three parts are there — the while loop just spreads them out:

int count = 0;              // initialization
while (count < 5) {         // condition
  System.out.println(count);
  count++;                  // update
}
for (int count = 0; count < 5; count++) {
  System.out.println(count);
}

Both print 0 through 4.

When to use which:

  • for loop — you know how many times to repeat, or you're counting through a range of numbers.
  • while loop — you repeat until something happens, and you don't know in advance how many times that will take (like while (amy.canMove())).

Scope of the loop control variable

A variable declared in the for loop header only exists inside the loop:

for (int i = 0; i < 3; i++) {
  System.out.println(i);
}
System.out.println(i);   // ERROR — i doesn't exist out here

If you need the value after the loop, declare the variable before the loop, or use a while loop.

3.31D Array Traversals

To traverse an array is to access its elements one by one. Traversing is how a program does anything with every element: print them, add them up, change them, or search for one.

The trick is to use a loop control variable as the index.

Traversing with a while loop

int[] scores = {75, 90, 83};
int index = 0;
while (index < scores.length) {
  System.out.println(scores[index]);
  index += 1;
}
75
90
83
  • index starts at 0 — the first element.
  • The condition index < scores.length keeps the loop going as long as index is a valid index.
  • scores[index] uses the current index to reach the current element.
  • index += 1 moves to the next element.
indexindex < 3Output
0true75
1true90
2true83
3false(loop ends)

Traversing with a for loop

The same traversal as a for loop — the standard way to traverse an array:

int[] scores = {75, 90, 83};
for (int index = 0; index < scores.length; index++) {
  System.out.println(scores[index]);
}

All three parts that were spread across the while loop now sit in the header. This is the pattern to know by heart:

for (int i = 0; i < arr.length; i++) {
  // arr[i] is the current element
}

Use <, not <=. With i <= arr.length, the last pass uses arr[arr.length], which throws an ArrayIndexOutOfBoundsException.

Modifying every element

Because you have the index, you can assign to each element as you go:

int[] nums = {2, 4, 6};
for (int i = 0; i < nums.length; i++) {
  nums[i] *= 2;
}
// nums is now {4, 8, 12}

This works with a while loop too. It does not work with an enhanced for loop (see 3.5).

Traversing backward

Start at the last index and count down to 0:

String[] pets = {"cat", "puppy", "hippo"};
for (int i = pets.length - 1; i >= 0; i--) {
  System.out.print(pets[i] + " ");
}
hippo puppy cat

All three parts change:

  • start at length - 1, not length
  • keep going while i >= 0, so index 0 is included
  • i-- to move backward

Here's a buggy backward traversal and its fix. Each of the three lines has one of those mistakes:

// Buggy
int[] nums = {10, 20, 30};
int index = nums.length;        // starts at 3 — out of bounds
while (index > 0) {             // skips index 0
  nums[index] += 5;
  index += 1;                   // moves the wrong way
}
// Fixed
int[] nums = {10, 20, 30};
int index = nums.length - 1;
while (index >= 0) {
  nums[index] += 5;
  index -= 1;
}

Traversing part of an array

A traversal doesn't have to visit every element. Change the start, the condition, or the update:

// every other element: indexes 0, 2, 4, ...
for (int i = 0; i < nums.length; i += 2)

// skip the first element
for (int i = 1; i < nums.length; i++)

// only the first half
for (int i = 0; i < nums.length / 2; i++)

Example — add 3 to every other element:

int[] values = {-5, 2, 8, 10, 17};
for (int i = 0; i < values.length; i += 2) {
  values[i] = values[i] + 3;
}
// values is now {-2, 2, 11, 10, 20}

Indexes 0, 2, and 4 changed. Indexes 1 and 3 were skipped.

ArrayIndexOutOfBoundsException in loops

An ArrayIndexOutOfBoundsException happens when code tries to access an index that is negative, or greater than or equal to the array's length. In a traversal, it almost always comes from one of these:

MistakeWhy it fails
i <= arr.lengththe last pass uses arr[arr.length]
starting a backward loop at arr.lengththe first pass uses arr[arr.length]
arr[i + 1] with i < arr.lengthon the last pass, i + 1 is arr.length
i-- in a loop that should count upi goes negative

When a traversal crashes, trace the first and last passes by hand. That's where the bad index almost always shows up.

3.4Text Files

Everything a program stores in variables disappears when the program stops. A file is storage for data that persists when the program is not running, and a program can read that data back while it runs.

A text file is a file that contains letters, numbers, and/or symbols but has no special formatting — like a .txt file.

Reading a text file is just one more way to fill an array or run an algorithm: instead of typing the values into an initializer list, the program reads them from the file.

The import statements

Three classes are involved, and none of them are available until you import them at the top of the file:

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
ClassPackageJob
Filejava.iorepresents the file on disk
IOExceptionjava.iothe error thrown when a file can't be opened
Scannerjava.utilreads values out of the file

The java.io package provides classes for input and output.

throws IOException

Java requires you to say what should happen if the file can't be opened — for example, if the file name is misspelled. One way is to add throws IOException to the header of any method that opens a file:

public static void main(String[] args) throws IOException {
public int findMax(String filename) throws IOException {

If the file name is invalid, the program terminates with an error. In this course, a method that calls a method declared with throws IOException needs throws IOException in its own header too — which is why main usually has it, and why the class containing main needs the import java.io.IOException; line as well.

Leaving off throws IOException is a compile error, not a runtime one. The code won't run at all.

Opening, reading, and closing a file

public void readFile(String filename) throws IOException {
  File file = new File(filename);
  Scanner scanner = new Scanner(file);
  String name = scanner.nextLine();
  scanner.close();
}
  1. Open the file by creating a File object, passing the file name to the constructor: new File(filename).
  2. Connect a Scanner to it by passing the File object to the Scanner constructor: new Scanner(file).
  3. Read with Scanner methods.
  4. Close the file with scanner.close() when the program is finished with it.

Scanner methods

These are the Scanner methods you need, and they're all on the AP Java Quick Reference:

MethodReturns
int nextInt()the next int in the file
double nextDouble()the next double in the file
boolean nextBoolean()the next boolean in the file
String next()the next String token — everything up to the next space or line break
String nextLine()the rest of the current line, as a String
boolean hasNext()true if there's another item to read; false otherwise
void close()closes the scanner — returns nothing

If you call nextInt(), nextDouble(), or nextBoolean() and the next item in the file isn't that type, Java throws an InputMismatchException.

Don't mix nextLine() with the other Scanner methods on the same file. They handle line breaks differently, so nextLine() can return an empty string right after a nextInt(). On the AP exam, code that mixes them is out of scope — read a file with nextLine() or with the others, not both.

Reading the whole file with hasNext()

You usually don't know how many values a file holds. Use a while loop with hasNext() as the condition — it keeps reading until there's nothing left:

public void printAll(String filename) throws IOException {
  File file = new File(filename);
  Scanner scanner = new Scanner(file);
  while (scanner.hasNext()) {
    System.out.println(scanner.nextLine());
  }
  scanner.close();
}

This is a job for a while loop, not a for loop: the loop runs until the file runs out, and you don't know in advance how many times that is.

Splitting a line into an array

split is a String method that breaks one string into an array of strings, cutting wherever it finds the separator you give it:

String data = "red, green, blue";
String[] colors = data.split(", ");
Index012
colors"red""green""blue"

The separator itself is removed. Combined with a file, it turns one line of comma-separated values into an array you can traverse:

public String[] parseData(String filename) throws IOException {
  File file = new File(filename);
  Scanner scanner = new Scanner(file);
  String data = scanner.nextLine();
  String[] splitData = data.split(", ");
  scanner.close();
  return splitData;
}

Stick to plain separators like ", ", " ", or ",". Characters such as . and * have special meanings inside split, and that's beyond this course.

Running an algorithm on a file

Any algorithm you'd run on an array works on a file too — you just get each value from the scanner instead of from an index. Finding the largest number in a file of int values:

public int findMax(String filename) throws IOException {
  File file = new File(filename);
  Scanner scanner = new Scanner(file);
  int max = scanner.nextInt();          // start with the first value
  while (scanner.hasNext()) {
    int current = scanner.nextInt();
    if (current > max) {
      max = current;
    }
  }
  scanner.close();
  return max;
}

Starting max at the first value in the file (rather than at 0) means the method still works if every number in the file is negative. The same idea is explained for arrays in 3.6.

3.5Enhanced For Loops

An enhanced for loop traverses an array from the first element to the last without using an index. It's the shortest way to visit every element in order.

int[] scores = {75, 90, 83};
for (int value : scores) {
  System.out.println(value);
}
75
90
83

Read the header as "for each value in scores."

The two parts of the header

for (int value : scores)
PartExampleWhat it is
Enhanced for loop variableint valueholds one element at a time
The arrayscoresthe array to traverse

They're separated by a colon. The variable's type must match the array's element type — an int[] needs an int variable, a String[] needs a String variable:

String[] names = {"Ana", "Ben", "Cy"};
for (String name : names) {
  System.out.println(name);
}

There's no index anywhere. On each pass, the variable simply is the next element.

The loop variable is a copy

On each pass, the enhanced for loop variable is assigned a copy of the element. Changing the copy does not change the array:

int[] scores = {75, 90, 83};
for (int value : scores) {
  value += 10;          // changes the copy only
}

for (int updated : scores) {
  System.out.println(updated);
}
75
90
83

The array is unchanged. To actually change the elements, you need the index — use a regular for loop:

for (int i = 0; i < scores.length; i++) {
  scores[i] += 10;      // changes the array
}

A classic test question: an enhanced for loop that adds to or reassigns its loop variable, followed by printing the array. The answer is always the original values.

Here's a trickier version — the loop variable changes, but only the copy is printed:

int[] arr = {10, 8, 14};

for (int j : arr) {
  j = j + 5;
  System.out.print(j + " ");
}
for (int j : arr) {
  System.out.print(j + " ");
}
15 13 19 10 8 14

The first loop prints the changed copies. The second shows the array was never touched.

Arrays of objects

When the elements are objects, the loop variable is a copy of the reference — so it points to the same object that's in the array. Calling a method on it does change that object:

Suppose a Shape class has a mutator setColor(String color) and a toString that reports its color:

Shape[] theShapes = { new Shape("red"), new Shape("cyan"), new Shape("pink") };
for (Shape aShape : theShapes) {
  aShape.setColor("purple");
}
for (Shape aShape : theShapes) {
  System.out.println(aShape);
}
Shape: purple
Shape: purple
Shape: purple

Every object in the array changed, because aShape pointed at each real object in turn.

What you still can't do is replace which object is stored in the array. Assigning aShape = new Shape("green"); only changes the copy.

Inside an enhanced for loop…Changes the array?
value += 10; on a primitiveNo
aShape = new Shape("green");No — replaces the copy only
aShape.setColor("purple"); on an objectYes — the object itself changes

When to use an enhanced for loop

Use one when:

  • you need every element, in order, starting at index 0
  • you're only reading the values — printing, adding them up, counting, searching

Use a regular for loop instead when:

  • you need the index (for example, to report where something is)
  • you need to change the values stored in the array
  • you want only part of the array, or a different order (backward, every other element)

Rewriting as a regular for loop

Any enhanced for loop can be rewritten as an indexed for loop or a while loop. Replace the loop variable with arr[i]:

for (int value : scores) {
  total += value;
}
for (int i = 0; i < scores.length; i++) {
  total += scores[i];
}

The reverse isn't always possible: a loop that uses the index, changes elements, or skips around can't become an enhanced for loop.

3.6Array Algorithms & Nested Loops

Most array problems — on tests and in FRQs — are a handful of standard algorithms wearing different names. Learn the shapes here and you'll recognize them whether the array holds test scores, ticket prices, or store sales.

Every one of them is a traversal (3.3 and 3.5) plus a variable that remembers something as the loop goes.

Each algorithm below has two solutions you can open: one with an enhanced for loop and one with a regular for loop that uses an index. Both visit every element. When the algorithm needs to know where an element is (its neighbor, its new position, or changing the array itself), the regular for loop is the better fit.

Where does the array come from? In a method, the array you traverse will be either a 1D array instance variable or a 1D array parameter.

  • Instance variable: declared in the class, like private double[] temps;. The method doesn't receive it; it just uses temps by name.
  • Parameter: passed into the method, like public int countName(String[] names, String name). The method uses names.

The loop is written the same way in both cases. Use whatever name the array has.

Sum

Start a total at 0, add each element.

Enhanced for loop solution
int total = 0;
for (int value : nums) {
  total += value;
}
Regular for loop solution
int total = 0;
for (int i = 0; i < nums.length; i++) {
  total += nums[i];
}

Average

Average is the sum divided by the number of elements. Watch the type: if both the sum and length are int, the division is integer division and the decimal is cut off.

int[] nums = {3, 4, 4};
int total = 0;
for (int value : nums) {
  total += value;
}
double avg = total / nums.length;   // 11 / 3 is 3, so avg is 3.0 — wrong

Keep the sum in a double so the division is a double division.

Enhanced for loop solution
double total = 0;
for (int value : nums) {
  total += value;
}
double avg = total / nums.length;   // 11.0 / 3 is 3.6666...
Regular for loop solution
double total = 0;
for (int i = 0; i < nums.length; i++) {
  total += nums[i];
}
double avg = total / nums.length;   // 11.0 / 3 is 3.6666...

Minimum and maximum

Keep track of the best value seen so far. Start it at the first element, then compare against every element.

Enhanced for loop solution
int largest = nums[0];
for (int value : nums) {
  if (value > largest) {
    largest = value;
  }
}
Regular for loop solution
int largest = nums[0];
for (int i = 0; i < nums.length; i++) {
  if (nums[i] > largest) {
    largest = nums[i];
  }
}
// Starting at i = 1 also works, since nums[0] is already in largest.

For the minimum, flip the comparison to <.

Why start at nums[0] and not at 0? If every value is negative, largest = 0 would never be replaced, and the method would return 0, which isn't even in the array. Starting at the first element always works.

Counting elements with a property

A counter starts at 0 and goes up by one each time an element passes the test.

Enhanced for loop solution
int evenCount = 0;
for (int value : nums) {
  if (value % 2 == 0) {
    evenCount++;
  }
}
Regular for loop solution
int evenCount = 0;
for (int i = 0; i < nums.length; i++) {
  if (nums[i] % 2 == 0) {
    evenCount++;
  }
}

Change the if condition to count anything — values over 100, empty strings, prices equal to 0.00.

Checking for odd numbers: use value % 2 != 0, not value % 2 == 1. In Java, -3 % 2 is -1, so == 1 misses negative odd numbers.

Counting matches for a parameter

The value to look for can come in as a parameter. This method counts how many times name appears in the array. Strings are objects, so compare them with equals, not == (see Comparing Strings below).

Enhanced for loop solution
public int countName(String[] names, String name) {
  int count = 0;
  for (String n : names) {
    if (n.equals(name)) {
      count++;
    }
  }
  return count;
}
Regular for loop solution
public int countName(String[] names, String name) {
  int count = 0;
  for (int i = 0; i < names.length; i++) {
    if (names[i].equals(name)) {
      count++;
    }
  }
  return count;
}

For a number parameter, use == instead: if (value == target).

Does at least one element have a property?

Return true as soon as you find one. Only return false after the loop, once you've checked everything.

Enhanced for loop solution
public boolean hasNegative(int[] nums) {
  for (int value : nums) {
    if (value < 0) {
      return true;     // found one — stop now
    }
  }
  return false;        // checked them all, found none
}
Regular for loop solution
public boolean hasNegative(int[] nums) {
  for (int i = 0; i < nums.length; i++) {
    if (nums[i] < 0) {
      return true;     // found one — stop now
    }
  }
  return false;        // checked them all, found none
}

Do all elements have a property?

Flip it: return false as soon as one element fails, and true only after the loop.

Enhanced for loop solution
public boolean allPassing(int[] scores) {
  for (int value : scores) {
    if (value < 70) {
      return false;    // one failure is enough
    }
  }
  return true;
}
Regular for loop solution
public boolean allPassing(int[] scores) {
  for (int i = 0; i < scores.length; i++) {
    if (scores[i] < 70) {
      return false;    // one failure is enough
    }
  }
  return true;
}

return inside a loop vs. at the end

return ends the method immediately, even in the middle of a loop. That's exactly what you want when one element settles the answer. It's a bug when the answer depends on every element:

// BUG — only ever looks at the first element
for (int value : scores) {
  if (value < 70) {
    return false;
  } else {
    return true;     // returns on the very first pass
  }
}

If an else branch has a return in it, the loop will never get past its first element. The "everything passed" answer belongs after the loop.

Pairs of neighboring elements

To compare each element with the next one, use the index, and stop one early so i + 1 stays in bounds. With i < nums.length, the last pass would use nums[nums.length] and crash.

Enhanced for loop solution
// An enhanced for loop has no index, so remember the previous value instead.
int increases = 0;
int previous = nums[0];
for (int value : nums) {
  if (value > previous) {
    increases++;
  }
  previous = value;
}
Regular for loop solution
int increases = 0;
for (int i = 0; i < nums.length - 1; i++) {
  if (nums[i + 1] > nums[i]) {
    increases++;
  }
}

Reversing into a new array

Element i of the original goes to position length - 1 - i of the new array.

iwords.length - 1 - i
03
12
21
30

(For an array of length 4.) The original array is left unchanged.

Enhanced for loop solution
// The enhanced for loop has no index, so keep your own position counter.
String[] reversed = new String[words.length];
int pos = words.length - 1;
for (String word : words) {
  reversed[pos] = word;
  pos--;
}
Regular for loop solution
String[] reversed = new String[words.length];
for (int i = 0; i < words.length; i++) {
  reversed[words.length - 1 - i] = words[i];
}

Shifting elements

To shift every element left by one, copy each element from its right-hand neighbor, then wrap the first element around to the end. That's called a rotation. For example, {1, 2, 3, 4} becomes {2, 3, 4, 1}.

Save nums[0] before the loop. Otherwise it's overwritten on the first pass and lost.

Enhanced for loop solution
// Assigning to the loop variable doesn't change the array, so this
// still needs an index to write into. The regular for loop is simpler here.
int first = nums[0];
int i = 0;
for (int value : nums) {
  if (i > 0) {
    nums[i - 1] = value;
  }
  i++;
}
nums[nums.length - 1] = first;
Regular for loop solution
int first = nums[0];
for (int i = 0; i < nums.length - 1; i++) {
  nums[i] = nums[i + 1];
}
nums[nums.length - 1] = first;

Comparing Strings: equals, not ==

Strings are objects. On objects, == checks whether two variables refer to the same object in memory, not whether they hold the same characters.

String s1 = "Hello";
String s3 = new String("Hello");

System.out.println(s1 == s3);        // false — two different objects
System.out.println(s1.equals(s3));   // true  — same characters

The equals method returns true when two strings contain the same sequence of characters.

You may see == give true for two string literals like "Hello" and "Hello". That happens because Java reuses identical literals behind the scenes, and you can't count on it.

To compare the contents of two Strings, always use equals. Use == for primitives (int, double, boolean).

Searching a String array uses the same pattern as any other search.

Enhanced for loop solution
public boolean contains(String[] names, String target) {
  for (String name : names) {
    if (name.equals(target)) {
      return true;
    }
  }
  return false;
}
Regular for loop solution
public boolean contains(String[] names, String target) {
  for (int i = 0; i < names.length; i++) {
    if (names[i].equals(target)) {
      return true;
    }
  }
  return false;
}

Nested loops

A nested loop is a loop inside another loop. The inner loop runs all of its passes for every single pass of the outer loop.

for (int outer = 1; outer <= 3; outer++) {
  for (int inner = 1; inner <= 2; inner++) {
    System.out.println(outer * inner);
  }
}
outerinnerOutput
111
122
212
224
313
326

The outer loop runs 3 times, and the inner loop runs 2 times each time, so the body runs 3 × 2 = 6 times.

When the inner loop depends on the outer loop

Sometimes the inner loop's condition uses the outer variable, so the inner loop runs a different number of times on each pass:

int total = 0;
for (int i = 1; i <= 4; i++) {
  for (int j = 1; j <= i; j++) {
    total = total + j;
  }
}
System.out.println(total);
iinner j valuesadded this passtotal
1111
21, 234
31, 2, 3610
41, 2, 3, 41020

Prints 20. Don't multiply here; trace each pass of the outer loop.

Finding duplicates

To check whether an array has any duplicate elements, compare every element with every element after it. That's a nested loop where the inner loop starts one past the outer:

public boolean hasDuplicates(int[] nums) {
  for (int i = 0; i < nums.length; i++) {
    for (int j = i + 1; j < nums.length; j++) {
      if (nums[i] == nums[j]) {
        return true;
      }
    }
  }
  return false;
}
  • j starts at i + 1, not 0. Starting at 0 would compare each element with itself (i == j), and every array would look like it had a duplicate.
  • Starting at i + 1 also avoids checking the same pair twice.
  • For a String array, compare with nums[i].equals(nums[j]) instead of ==.
VocabularyUnit 3 Vocab

Data Set — A collection of related pieces of information organized together to analyze, answer questions, or solve problems.

Value — A single item in a data structure.

Data Structure — A structure for organizing, processing, retrieving, and storing data.

Element — A single value or object in a data structure.

One-Dimensional (1D) Array — A data structure that holds multiple values of the same data type. Its size is fixed once it's created.

Initializer List — A comma-separated list of values or objects given inside curly braces ({ }), used to create an array with those values.

Index — An integer that indicates the position of a value in a data structure. Array indexes start at 0 and end at length - 1.

length — The number of elements an array can store, accessed as arrayName.length (no parentheses).

ArrayIndexOutOfBoundsException — The error thrown when code uses an index that is negative, or greater than or equal to the array's length.

Data Abstraction — Managing complexity by giving data a name, like a variable or an array, so you can focus on what the data means rather than how it's stored.

Traverse — To access the elements in a data structure one by one.

for Loop — A loop whose header holds three parts: the initialization, the condition, and the update.

Loop Control Variable — A variable that is changed by a constant value and determines when a loop ends.

Increment — To increase a value by one (++).

Decrement — To decrease a value by one (--).

Off-by-One Error — An error where a loop repeats one time too many or one time too few.

File — Storage for data that persists when the program is not running.

Text File — A file that contains letters, numbers, and/or symbols but has no special formatting.

Enhanced for Loop — A loop that traverses an array from the first element to the last without using an index, written for (type variable : array).

Enhanced for Loop Variable — The variable in an enhanced for loop's header. On each pass it holds a copy of the next element.

Standard Algorithm — A common, reusable pattern for processing data, such as finding a sum, average, minimum, or maximum, counting, or searching.

Nested Loop — A loop inside of another loop. The inner loop finishes all of its passes for each single pass of the outer loop.