Writing robot software requires more than syntax knowledge: it demands defensive programming. In a competitive match, an uncaught runtime exception or incorrect physical unit will disable your robot on the field.
Before constructing subsystem classes, you must understand Java language fundamentals and how WPILib leverages object encapsulation, functional interfaces, and dimensional analysis to write reliable, crash-proof robot code.
Students should have completed Stage 00 (toolchain installation) and Stage 01 (hardware commissioning in Phoenix Tuner X) before starting this lesson.
Core Java Programming Fundamentals
Section titled “Core Java Programming Fundamentals”1. Variables, Data Types, and Arithmetic
Section titled “1. Variables, Data Types, and Arithmetic”Java is a statically typed language. Every variable must have a declared type before it can store data:
// Primitive data types for numeric calculations and hardware stateint canBusId = 14; // 32-bit integer for CAN IDs and countsdouble targetVelocityRpm = 4500.0; // 64-bit floating point for velocities and anglesboolean isElevatorAtBottom = true; // True/false flag for limit switches
// Basic arithmetic expressionsdouble gearReduction = 25.0 / 1.0;double wheelDiameterMeters = 0.1016; // 4-inch wheeldouble wheelCircumference = wheelDiameterMeters * Math.PI;2. Conditional Control Flow & Boolean Logic
Section titled “2. Conditional Control Flow & Boolean Logic”Robot mechanisms must make instant decisions based on sensor inputs. The if, else if, and else statements evaluate boolean expressions to choose an execution branch:
// Operator command and motor output variablesdouble commandedSpeed = -0.5; // Operator commanding downward retreatdouble motorSpeed = 0.0;
// Sensor readings from hardwaredouble currentHeightInches = 50.2;double maxHeightInches = 50.0;boolean lowerLimitSwitchPressed = false;
// Relational operators: <, >, <=, >=, ==, !=// Logical operators: && (AND), || (OR), ! (NOT)if (currentHeightInches >= maxHeightInches && commandedSpeed > 0.0) { // Upper soft limit reached: block upward motion, permit downward retreat motorSpeed = 0.0;} else if (lowerLimitSwitchPressed && commandedSpeed < 0.0) { // Physical lower limit hit: block downward motion, permit upward retreat motorSpeed = 0.0;} else { // Safe to run commanded speed in requested direction motorSpeed = commandedSpeed;}3. Methods, Signatures, and Return Values
Section titled “3. Methods, Signatures, and Return Values”Methods are reusable blocks of code that perform actions or calculate values. Every method defines an access modifier (public or private), a return type (void if it returns nothing, or a specific type like double), a name, and parameter inputs:
public class DrivetrainMath { // 1. A query method that calculates and returns a double public static double applyDeadband(double input, double threshold) { if (Math.abs(input) < threshold) { return 0.0; // Return zero when inside deadband } return input; }
// 2. A command method that performs an action without returning a value public static void logMotorSpeed(String motorName, double speed) { System.out.println(motorName + " running at: " + (speed * 100.0) + "%"); }}4. Classes, Constructors, and Object Instantiation
Section titled “4. Classes, Constructors, and Object Instantiation”A class is a blueprint that defines data fields (state) and methods (behavior). An object is a live instance of that blueprint created in computer memory using the new keyword:
// The Class Blueprintpublic class RollerMechanism { // Fields: state stored inside each instance private final int m_canId; private double m_currentSpeed;
// Constructor: executes once when the object is instantiated public RollerMechanism(int canId) { this.m_canId = canId; this.m_currentSpeed = 0.0; }
// Public method to command the roller public void setSpeed(double speed) { this.m_currentSpeed = speed; // In real robot code: motor.set(speed); }
// Public method to query the speed public double getSpeed() { return this.m_currentSpeed; }}
// Instantiating and using objects:RollerMechanism intakeRoller = new RollerMechanism(12);intakeRoller.setSpeed(0.85);5. Reference Types vs. Primitive Types
Section titled “5. Reference Types vs. Primitive Types”Understanding how Java handles memory is critical to avoiding the most common runtime bug in robotics: the NullPointerException.
- Primitives (
double,int,boolean): The variable holds the actual binary data directly. Primitives have default numeric values (0.0,0,false) and can never benull. - References (
TalonFX,CANcoder,String, arrays): The variable holds a memory address pointing to an object created on the heap. Before instantiation withnew, reference variables point tonull. Attempting to call a method on an uninstantiated reference crashes the robot code instantly:
// DANGER: Uninitialized hardware referenceTalonFX m_climberMotor; // Currently null!
// Calling methods before "new" crashes code during initialization:// m_climberMotor.set(0.5); // Throws NullPointerException!
// CORRECT: Always instantiate references in the constructor:m_climberMotor = new TalonFX(18, "rio");m_climberMotor.set(0.5); // Safe: references a real hardware object6. Arrays and Iteration Loops
Section titled “6. Arrays and Iteration Loops”When controlling multiple identical mechanisms (such as 4 swerve modules or 8 drivetrain motor controllers), arrays store fixed-size ordered collections:
// Array declaration and initializationint[] swerveDriveCanIds = {1, 3, 5, 7};
// Traditional for loop: index-based iterationfor (int i = 0; i < swerveDriveCanIds.length; i++) { System.out.println("Configuring drive module " + i + " on CAN ID: " + swerveDriveCanIds[i]);}
// Enhanced for-each loop: direct element iterationfor (int canId : swerveDriveCanIds) { System.out.println("Pinging CAN device ID: " + canId);}1. Object Encapsulation for Hardware
Section titled “1. Object Encapsulation for Hardware”Every mechanical mechanism on the robot must be encapsulated in a dedicated subsystem class. Hardware handles (such as TalonFX or CANcoder) must be declared with private final visibility.
package frc.robot.subsystems;
import edu.wpi.first.wpilibj2.command.SubsystemBase;import com.ctre.phoenix6.hardware.TalonFX;import com.ctre.phoenix6.hardware.CANcoder;
public class ArmSubsystem extends SubsystemBase { // Hardware handles are private and final private final TalonFX m_motor; private final CANcoder m_encoder;
public ArmSubsystem(int motorId, int encoderId, String canbus) { m_motor = new TalonFX(motorId, canbus); m_encoder = new CANcoder(encoderId, canbus); }}Why private final Matters:
Section titled “Why private final Matters:”private: Prevents external classes (like autonomous commands or button bindings) from commanding arbitrary voltages or modifying motor configurations directly. All physical operations must go through public subsystem methods.final: Guarantees that the motor handle is initialized in the constructor and cannot be reassigned or set tonullduring match play.
2. Java Lambdas and Method References
Section titled “2. Java Lambdas and Method References”The WPILib command framework uses functional interfaces to evaluate conditions dynamically during execution. Instead of creating verbose anonymous classes, use lambdas (() -> ...) or method references (this::method):
// 1. DoubleSupplier lambda: Reads joystick Y-axis every 20msDoubleSupplier forwardSpeed = () -> -m_driverController.getLeftY();
// 2. BooleanSupplier method reference: Checks if beam-break is trippedBooleanSupplier hasNote = m_indexer::isGamePieceDetected;When binding default drive commands, pass lambdas to the subsystem command factory so changes in joystick displacement are read continuously in the main 20ms loop:
m_drivetrain.setDefaultCommand( m_drivetrain.driveCommand( () -> -m_driverController.getLeftY(), () -> -m_driverController.getLeftX(), () -> -m_driverController.getRightX() ));3. Type-Safe Physical Units with WPILib Units
Section titled “3. Type-Safe Physical Units with WPILib Units”A common bug in FRC is passing raw numeric values without knowing whether the method expects rotations, radians, inches, or meters. WPILib’s edu.wpi.first.units.* library eliminates unit mismatch bugs at compile time.
import static edu.wpi.first.units.Units.*;import edu.wpi.first.units.measure.Angle;import edu.wpi.first.units.measure.AngularVelocity;import edu.wpi.first.units.measure.Distance;
public class MechanismMath { // Methods accept explicit unit types public static AngularVelocity calculateFlywheelTarget(Distance distanceToSpeaker) { if (distanceToSpeaker.in(Meters) > 4.0) { return RPM.of(5000); } else { return RPM.of(3500); } }
public static void setArmGoal(Angle targetAngle) { // Safely extract the desired unit for Phoenix 6 (Rotations) double motorRotations = targetAngle.in(Rotations); // m_armMotor.setControl(new PositionVoltage(motorRotations)); }}Check Your Work
Section titled “Check Your Work”Validate your Java code against these quality checks before moving to the command lifecycle:
- Clean Compilation: Confirm the project builds without errors using
./gradlew compileJava. - Encapsulation Audit: Verify that all motor controllers, CANcoders, and limit switch objects are declared
private final. No other class should be able to call.set()or.setVoltage()on them directly. - Null Check: Confirm that all
finalhardware fields are assigned a non-null instance inside the subsystem constructor. - Unit Safety: Replace raw
doubleparameters representing physical angles or distances withAngleandDistancetypes fromedu.wpi.first.units.Units.
Verified Sources & Standards
- WPILib Java Programming Basicsdocs.wpilib.orgWPILib Standard
- Oracle Java Tutorials - Language Basicsdocs.oracle.comHardware Vendor
- WPILib Units Library Guidedocs.wpilib.orgWPILib Standard