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!
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
scores[4] on a 4-element array crashes with ArrayIndexOutOfBoundsException β valid indexes only go from 0 to scores.length - 1.
Mini quiz β array basicsβ
Array basics
1 / 2int[] 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!
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β
Looping over arrays
1 / 2Which 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β
- An array holds many values of the same type under one name; each value is reached by its index, starting at
0. .lengthis a field, not a method β no parentheses. Valid indexes run from0tolength - 1.- 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. - Reading past the end (or before the start) throws
ArrayIndexOutOfBoundsExceptionat runtime β Java will not let you silently read garbage memory.
Exercisesβ
Read an integer n, then n integers. Print them in reverse order, space-separated.