Skip to main content

Chapter 8a - Arrays

What Is an Array?​

Up to now, one variable has held one value. An array is a single variable that holds a fixed-size list of values, all of the same type, side by side in memory. Each value has a position called its index, starting at 0.

public class Main {
public static void main(String[] args) {
int[] scores = {90, 85, 77, 100}; // an array literal
System.out.println(scores[0]); // 90 - first element
System.out.println(scores[3]); // 100 - last element
System.out.println(scores.length); // 4 - how many slots (no parentheses!)
}
}

πŸ§ͺ Try the code out!

Two ways to make an array
int[] scores = {90, 85, 77, 100}; // literal, size and values fixed at creation
int[] empty = new int[5]; // size 5, every slot starts at 0
Index out of bounds

scores[4] on a 4-element array crashes with ArrayIndexOutOfBoundsException β€” valid indexes only go from 0 to scores.length - 1.


Mini quiz β€” array basics​

Quiz

Array basics

1 / 2

int[] nums = {5, 10, 15}; What is nums[2]?

int[] nums = {5, 10, 15};

Pick an answer to see if you are right.


Looping Over an Array​

Two common ways to visit every element:

public class Main {
public static void main(String[] args) {
int[] scores = {90, 85, 77, 100};

// classic index loop - use this when you need the position too
for (int i = 0; i < scores.length; i++) {
System.out.println("Index " + i + " = " + scores[i]);
}

// for-each loop - use this when you only need the values
for (int s : scores) {
System.out.println("Score: " + s);
}
}
}

πŸ§ͺ Try the code out!

Which loop to use?

Use the index (for (int i = 0; ...)) loop when you need to know where something is, change a value, or compare neighbors. Use the for-each (for (int s : scores)) loop when you just need to look at every value once.


Mini quiz β€” looping and mutating​

Quiz

Looping over arrays

1 / 2

Which loop would you use to double every value in an array in place?

Pick an answer to see if you are right.


Challenge: sum of an array​

Read an integer n, then read n integers on the next line. Print their sum.


Challenge: find the max​

Read an integer n, then read n integers. Print the largest value.


Chapter summary​

Key takeaways
  1. An array holds many values of the same type under one name; each value is reached by its index, starting at 0.
  2. .length is a field, not a method β€” no parentheses. Valid indexes run from 0 to length - 1.
  3. Use an index loop (for (int i = 0; ...)) when you need position or want to change values; use a for-each loop (for (int v : arr)) when you only need to read each value once.
  4. Reading past the end (or before the start) throws ArrayIndexOutOfBoundsException at runtime β€” Java will not let you silently read garbage memory.

Exercises​

Activity: Reverse print

Read an integer n, then n integers. Print them in reverse order, space-separated.