Array Creation and Access
What an Array Is
An array is a fixed-size block of memory holding several values of the same type, accessed by position (index) instead of by separate variable names — the fix for needing motor1, motor2, motor3... variables.
int[] canBusIds = {1, 2, 3, 4}; // an initializer list — size inferred, values set immediately
Two Ways to Create One
int[] canBusIds; // declares the variable — no array exists yet (it's null)
canBusIds = new int[4]; // creates a 4-element array — all elements start at 0
int[] canBusIds2 = {1, 2, 3, 4}; // initializer list: create + fill in one step
An array is itself an object — a declared-but-not-yet-created array variable holds null, exactly like any other reference type.
When you create an array with new and a size, every element starts at that type's default: 0 for int, 0.0 for double, false for boolean, null for String or any reference type.
Indexing
Indices start at 0; the last valid index is always length - 1 (a public final int field, not a method — no parentheses, unlike String.length()).
System.out.println(canBusIds.length); // 4
canBusIds[0] = 5; // assign
System.out.println(canBusIds[0]); // read — prints 5
Accessing an index outside 0 to length - 1 throws ArrayIndexOutOfBoundsException — one of the most common real runtime errors.
Parallel Arrays
Two (or more) arrays, kept in the same order, where index i in one corresponds to index i in the other:
String[] autoNames = {"3-Piece-Left", "1-Piece-Safe", "Mobility-Only"};
double[] autoTimes = {14.2, 8.5, 3.1}; // autoTimes[i] is the recorded time for autoNames[i]
Arrays of Objects
An array can hold any type, including your own classes — but each element still has to be constructed individually:
TalonFX[] driveMotors = new TalonFX[4]; // 4 slots, all currently null
driveMotors[0] = new TalonFX(1); // must construct each element separately
driveMotors[0].set(0.5); // then call methods through the index
Common Pitfalls
- Forgetting an array must be constructed, not just declared.
int[] canBusIds;alone isnull— you neednew int[size]or an initializer list before using it. - Off-by-one on the last index. The last valid index is
length - 1, notlength. - Forgetting to construct each element of an object array.
new TalonFX[4]gives you 4nullslots, not 4 ready-to-use motor objects — each one still needs its ownnew TalonFX(...).
Key Takeaways
- An array is a fixed-size, same-type collection, accessed by a 0-based index.
new type[size]creates an array with every element at its type's default; an initializer list creates and fills it in one step.lengthis a field (no parentheses); the last valid index islength - 1.- Parallel arrays keep related data in sync by index.
- An array of objects still requires constructing each element individually — the array itself doesn't build the objects for you.
Derived from csawesome-2026: unit-4-data-collections/4.03-array-creation-and-access.md (CSA 4.3)