Declaring an array
java
int[] scores; // declares an array of ints
String[] names; // declares an array of Strings
double[] prices; // declares an array of doubles
Creating an array with `new`
java
int[] scores = new int[5]; // creates array of 5 ints
Default values by type
Initializer list
java
int[] scores = {95, 87, 73, 91, 88};
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};
java
int[] scores = new int[5];
scores[0] = 95;
scores[1] = 87;
scores[2] = 73;
scores[3] = 91;
scores[4] = 88;
Accessing elements
java
int[] scores = {95, 87, 73, 91, 88};
System.out.println(scores[0]); // 95 — first element
System.out.println(scores[2]); // 73 — third element
System.out.println(scores[4]); // 88 — last element
Modifying elements
java
scores[2] = 80; // change third element from 73 to 80
The `.length` property
java
int[] scores = {95, 87, 73, 91, 88};
System.out.println(scores.length); // 5
Accessing the last element
java
int last = scores[scores.length - 1]; // 88
ArrayIndexOutOfBoundsException
java
int[] scores = {95, 87, 73, 91, 88};
System.out.println(scores[5]); // RUNTIME ERROR!
System.out.println(scores[-1]); // RUNTIME ERROR!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
Arrays are reference types
java
int[] a = {1, 2, 3};
int[] b = a; // b points to the SAME array
b[0] = 99;
System.out.println(a[0]); // 99 — both see the change!
Memory diagram
a ──┐
├──▶ [99, 2, 3]
b ──┘
Comparing arrays
java
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b); // false — different objects!
Complete example: Student grade tracker
java
public class GradeTracker {
public static void main(String[] args) {
// Create array for 4 test scores
int[] tests = new int[4];
// Record scores
tests[0] = 92;
tests[1] = 85;
tests[2] = 78;
tests[3] = 96;
// Print all scores
System.out.println("Test scores:");
for (int i = 0; i < tests.length; i++) {
System.out.println(" Test " + (i + 1) + ": " + tests[i]);
}
// Find highest score
int max = tests[0];
for (int i = 1; i < tests.length; i++) {
if (tests[i] > max) {
max = tests[i];
}
}
System.out.println("Highest: " + max);
}
}
Test scores:
Test 1: 92
Test 2: 85
Test 3: 78
Test 4: 96
Highest: 96
AP Exam Tips
- •
- •
- •
- •
- •
- •