Skip to content
learnFRC.org
programminglessonbeginner35 min

Java Foundations for FRC Robotics

Master Java fundamentals, object encapsulation, private final hardware handles, lambdas, and type-safe WPILib Units before writing subsystem code.

What you will learn

  • Master Java core concepts: primitive types, control flow, methods, classes, and loops.
  • Apply private final encapsulation to prevent external classes from corrupting motor state.
  • Implement functional interfaces, lambdas, and method references for dynamic command evaluation.
  • Utilize edu.wpi.first.units.* to eliminate dimension and unit mismatch runtime errors.

Prerequisites:Position Closed-Loop & Motion Magic

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.

Prerequisites

Students should have completed Stage 00 (toolchain installation) and Stage 01 (hardware commissioning in Phoenix Tuner X) before starting this lesson.

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 state
int canBusId = 14; // 32-bit integer for CAN IDs and counts
double targetVelocityRpm = 4500.0; // 64-bit floating point for velocities and angles
boolean isElevatorAtBottom = true; // True/false flag for limit switches
// Basic arithmetic expressions
double gearReduction = 25.0 / 1.0;
double wheelDiameterMeters = 0.1016; // 4-inch wheel
double 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 variables
double commandedSpeed = -0.5; // Operator commanding downward retreat
double motorSpeed = 0.0;
// Sensor readings from hardware
double 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;
}

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 Blueprint
public 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);

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 be null.
  • References (TalonFX, CANcoder, String, arrays): The variable holds a memory address pointing to an object created on the heap. Before instantiation with new, reference variables point to null. Attempting to call a method on an uninstantiated reference crashes the robot code instantly:
// DANGER: Uninitialized hardware reference
TalonFX 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 object

When controlling multiple identical mechanisms (such as 4 swerve modules or 8 drivetrain motor controllers), arrays store fixed-size ordered collections:

// Array declaration and initialization
int[] swerveDriveCanIds = {1, 3, 5, 7};
// Traditional for loop: index-based iteration
for (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 iteration
for (int canId : swerveDriveCanIds) {
System.out.println("Pinging CAN device ID: " + canId);
}

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);
}
}
  • 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 to null during match play.

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 20ms
DoubleSupplier forwardSpeed = () -> -m_driverController.getLeftY();
// 2. BooleanSupplier method reference: Checks if beam-break is tripped
BooleanSupplier 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));
}
}

Validate your Java code against these quality checks before moving to the command lifecycle:

  1. Clean Compilation: Confirm the project builds without errors using ./gradlew compileJava.
  2. 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.
  3. Null Check: Confirm that all final hardware fields are assigned a non-null instance inside the subsystem constructor.
  4. Unit Safety: Replace raw double parameters representing physical angles or distances with Angle and Distance types from edu.wpi.first.units.Units.

Verified Sources & Standards

Evergreen Standard