Summer · Week 4 of 8
Arrays & Methods
Storing lists of data and writing reusable blocks of code.
Arrays
An array stores multiple values of the same type in one variable. Fixed size — once you create it, you can't add or remove slots.
java
// Method 1: declare size, fill later (defaults to 0 / false / null) int[] motorIDs = new int[4]; motorIDs[0] = 1; motorIDs[1] = 2; // Method 2: declare with values directly double[] speeds = {0.5, 0.75, 1.0, -0.5}; // Access by index — ALWAYS starts at 0 System.out.println(speeds[0]); // 0.5 System.out.println(speeds.length); // 4
Index out of bounds: Accessing an index that doesn't exist (like arr[4] on a 4-element array) throws an ArrayIndexOutOfBoundsException and crashes your program. This is one of the most common runtime errors in Java.
Methods
A method is a named, reusable block of code. Instead of writing the same logic in 10 places, write it once as a method and call it anywhere.
java — method anatomy
// access return-type name parameters public static double calcWheelRPM(double motorRPM, double gearRatio) { return motorRPM / gearRatio; } // Call it: double wheelSpeed = calcWheelRPM(5400.0, 8.46); // 638.3...
Return type
What it sends back
The type of value the method returns. Use
void when it returns nothing.Parameters
Inputs to the method
Variables declared in the parentheses. The method gets a copy of whatever you pass in.
return
Sends back a value
Ends the method and returns a value to the caller. Void methods can use bare
return; or omit it.static
No object needed
A static method belongs to the class, not an instance. Call it as
ClassName.method().Javadocs
Special comments that describe your methods for teammates. Essential on a team where multiple people touch the same code.
java
/** * Calculates wheel RPM from motor RPM and gear ratio. * * @param motorRPM the motor's free-spin RPM * @param gearRatio the reduction ratio (e.g. 8.46 means motor spins 8.46x faster) * @return the resulting wheel RPM */ public static double calcWheelRPM(double motorRPM, double gearRatio) { return motorRPM / gearRatio; }
Fill in the Blanks
// Method that returns nothing, takes a double speed param
public static setSpeed(double speed) { }
public static setSpeed(double speed) { }
// Return the sum of a and b
public static int add(int a, int b) { }
public static int add(int a, int b) { }
// Access the 3rd element (index 2) of array arr
int val = arr[];
int val = arr[];