Operators
Operators are the verbs of Java — they act on your variables to produce results. On a robot, those results become motor outputs, enable conditions, safety gates, and state transitions. Getting operators wrong doesn't usually crash the program. It just makes the robot do the wrong thing, and figuring out why is the hard part.
By the end of this lesson, you will:
- Use arithmetic, assignment, comparison, logical, and unary operators correctly in robot code
- Explain short-circuit evaluation and why
&&and||are preferred over&and|for boolean logic - Predict the result of an expression involving mixed types, operator precedence, and compound assignment
- Identify the
=vs==bug by sight and explain exactly what each one does - Apply
%(modulo) to real robot problems — wrapping angles, cycling through modes
Operators as Robot Decisions
Every useful thing your robot code does involves an operator. Scaling joystick input to a motor: arithmetic. Checking whether a limit switch is triggered: comparison. Enabling a mechanism only when the right button is held and the arm is in range: logical. Accumulating distance traveled: compound assignment.
Operators fall into five categories. Use the explorer below to learn each one in context — not in the abstract, but in terms of the robot calculation it produces.
Compound Assignment in the Robot Loop
Compound assignment operators (+=, -=, *=, /=, %=) combine an arithmetic operation with assignment. They are syntactic shorthand, but they show up constantly in robot code for a reason: the robot loop runs 50 times per second, and many values are updated incrementally on each cycle.
This is one of the clearest examples of the mechanical–software relationship in this course. When a motor goes from 0 to full speed instantaneously, the mechanical shock can strip a gear, snap a chain, or bend a shaft. A software ramp rate — a few lines of += in the periodic loop — absorbs that shock in code before it reaches the hardware. Many vendor motor controllers have built-in ramp rate settings, but understanding how to implement it manually is the foundation for understanding theirs.
Modulo: The Operator FRC Programmers Underuse
The % operator returns the remainder after integer division. It doesn't appear in many beginner examples, but it shows up in robot code more than you'd expect — particularly anywhere the robot needs to wrap a value within a range or cycle through a fixed set of options.
FRC Use 1 — Cycling through autonomous modes
FRC Use 2 — Wrapping angles to stay within [0, 360)
Angle wrapping is one of the most common sources of swerve drive bugs I see during inspection and at events. Teams use a heading controller to keep the robot pointed in a direction, the raw encoder value crosses 0° or 360°, and the controller suddenly sees a 359° error instead of a 1° error — causing the robot to spin a full rotation instead of making a tiny correction. The fix is always some form of angle wrapping, and modulo is typically at the heart of it. Unit 7 covers this in full for swerve, but the operator is here.
Logical Operators and Short-Circuit Evaluation
Logical operators combine boolean expressions. On a robot, they are your safety gates and enable conditions. "Run the shooter only if the button is held and the intake is clear" is a logical AND. "Trigger a fault if the current is too high or the temperature exceeds the limit" is a logical OR.
Interactive truth table
Toggle A and B to see how &&, ||, and ! evaluate for every combination.
Short-circuit evaluation
Java's && and || are short-circuit operators: they stop evaluating as soon as the result is certain. For &&, if the left side is false, the right side is never evaluated — the whole expression is already false. For ||, if the left side is true, the right side is skipped.
This matters in robot code whenever the right-hand condition could throw an error or produce a side effect if evaluated on a null or uninitialized object.
The single & (bitwise AND) and | (bitwise OR) evaluate both sides regardless of the result — no short-circuit. For boolean expressions in if statements, you almost always want && and ||. The single-character versions are for bitwise operations on integers (like manipulating CAN bus message fields or LED control registers). Using & where you mean && in a safety condition is a subtle bug that only appears when the right-hand expression has a side effect — like incrementing a counter or calling a method that throws on a bad sensor state.
The Most Expensive Typo in FRC: = vs ==
Assignment (=) stores a value. Comparison (==) checks whether two values are equal. They look nearly identical and do completely different things. Using one where you meant the other is one of the most common bugs across all experience levels, and in some cases the Java compiler will catch it — but not always.
Java will warn you if you write if (someBoolean = true) — the compiler knows that assignment inside a condition is probably a mistake. But if (someInt = 5) will not compile at all because an int assignment doesn't produce a boolean. The dangerous case is specifically a boolean on the left side, because a boolean assignment does produce a valid condition.
Operator Precedence
When an expression has multiple operators, Java evaluates them in a fixed order — higher-precedence operators run first. The order roughly mirrors standard math: multiplication before addition, for example. The full precedence table is long, but knowing the key tiers is enough to write robot code without surprises.
The precedence rule that catches robot programmers most often: && binds tighter than ||. A mixed condition reads differently than it looks.
The rule of thumb used on 2910: if a condition has more than two operands, add parentheses. The compiler doesn't care. Your teammates at midnight before a regional will.
A team had a fault detection condition that was supposed to cut motor power when either of two sensors read out of range and the mechanism was active. Without parentheses, the && bound to only the second sensor — so the first sensor alone could trigger the cutoff even when the mechanism was idle. The robot would randomly stop mid-match. The code was correct in the programmer's head; operator precedence made it wrong on the field. Adding four characters — two pairs of parentheses — fixed it.
🔌 System Check
These aren't hypothetical — each one has caused a robot to behave unexpectedly at competition.
- Integer division truncating a motor output to zero. If any motor output calculation involves dividing two
intvalues, the result is always an integer. A command intended to set 50% speed evaluates to 0. Review every division that feeds into amotor.set()call and ensure at least one operand is adouble. - The
=vs==boolean assignment bug. Writingif (intakeRunning = true)makes the condition always true — the intake runs regardless of any other state. Java will warn on this, but warnings get ignored under time pressure. Preferif (intakeRunning)to avoid the ambiguity entirely. - Unparenthesized mixed
&&/||conditions. Any safety gate or enable condition with more than two operands must have explicit parentheses. "I'm pretty sure the precedence is right" is not good enough for code that controls hardware capable of injuring someone. - Ramp rate missing from high-inertia mechanisms. Arms, elevators, and climbers with significant mass need software ramp rates even if the motor controller has one — because mechanical shock on enable can strip gears before the controller's configured ramp engages. If your mechanism ever jerks at enable, check what your output looks like in the first five loop cycles.
- Modulo with negative values. Java's
%operator can return negative remainders when the dividend is negative. Angle wrapping and mode cycling that only ever get positive inputs are fine. Any calculation that might go negative needs the((x % n) + n) % npattern to guarantee a positive result.
Knowledge Check
Click an answer to check your understanding.
output after this executes, and what physical consequence would this have on a robot motor?
int speed = 1; int divisor = 2; double output = speed / divisor;if (tempSensor != null && tempSensor.getTemp() > 80.0). Why is && specifically the right operator here, rather than &?Build a Shooter Enable Condition
The following class skeleton represents a simplified shooter subsystem. Your job is to implement the operator logic — no WPILib hardware required, just pure Java logic. You can run this as a standalone Java class with a main() method.
- Implement all five methods using only operators covered in this lesson. Use parentheses explicitly in every multi-operand condition.
- Add a
main()method that tests all four combinations ofshootButtonHeldandintakeClearforshouldShoot(), printing the result for each. Verify the truth table matches your expectation from the interactive table above. - Test
nextAutoMode()in a loop — call it 10 times starting from mode 0 and print the mode after each call. Confirm it cycles correctly. - Bonus: The
getRampedSpeed()method currently ramps up. Modify it to also ramp down — if the current speed is above the target, decrement by 200 RPM/cycle toward the target instead of stopping immediately. What operator change is needed?