Programming Basics: Variables, Data Types, and Operators
Robot code has to remember things (a sensor reading, a motor output, whether a button is pressed) and do math or comparisons with them. Variables, data types, and operators are how you do both. Everything else in WPILib is built on top of these.
Variables: Named Boxes for Data
Section titled “Variables: Named Boxes for Data”A variable is a named box that holds a value. In Java you say what kind of value it holds when you create it:
int motorPort = 3;double speed = 0.75;boolean isEnabled = true;The pattern is always type name = value;. Creating the box is declaring ; putting a value in is assigning. After that, reuse the name without the type:
speed = 0.5;Name variables for what they hold — armAngle, not x. Java convention is camelCase.
Data Types: What Kind of Value?
Section titled “Data Types: What Kind of Value?”Java checks every variable’s type before the program runs, so a typo like assigning text to a number won’t compile instead of crashing mid-match. The four types you’ll use constantly in FRC:
int— a whole number, e.g. a CAN ID or PWM port like3, or a counter.double— a decimal number, e.g. a motor output0.75or a distance in meters.boolean— onlytrueorfalse: “is the limit switch pressed?”String— text like"intake". It’s an object, not a primitive, which is why it’s capitalized.
byte, short, long, float, and char exist too, but you’ll rarely reach for them as a beginner.
This matters in FRC: WPILib motor outputs are doubles from -1.0 (full reverse) to 1.0 (full forward). Store one in an int and you throw away the decimal — your robot only ever stops or slams to full speed.
Operators
Section titled “Operators”- Arithmetic:
+ - * / %(%is remainder). Trap:int / inttruncates, so5 / 2is2. Make one side a double (5.0 / 2) to get2.5— easy to hit when converting encoder ticks to distance. - Comparison:
==,!=,<,>,<=,>=— each produces aboolean. - Logical:
&&(and),||(or),!(not), e.g.isEnabled && !isStopped. - Assignment shortcuts:
count += 1;is the same ascount = count + 1;.
The classic beginner bug: = assigns , == compares. if (ready = true) is wrong; write if (ready).
Putting It Together
Section titled “Putting It Together”double batteryVoltage = 12.4;boolean lowBattery = batteryVoltage < 11.5; // false heredouble outputSpeed = lowBattery ? 0.3 : 0.75; // ternary: compact if/elseWith just these three ideas you can already describe most of what a robot tracks every cycle.
Key takeaways
Section titled “Key takeaways”- A variable is a named, typed box:
type name = value;— declare once, reassign freely. - Java is statically typed; the FRC workhorses are
int,double,boolean, andString. - Motor outputs are
doublevalues from -1.0 to 1.0, so never store them asint. int / inttruncates (5/2 == 2); use adoubleoperand for decimal results.=assigns a value;==compares — mixing them up is a top beginner bug.
This lesson was adapted from learnfrc.com.
