Skip to content
Week 4 · Lesson 1 45 min

Programming Concepts in Java

Learn the four building blocks of every robot program: variables, conditionals, loops and methods, written in the Java language used by the FTC SDK.

In this lesson you will

  • Explain what a program is and how a computer runs it one line at a time.
  • Declare and update variables of type int, double, boolean and String.
  • Write if/else conditionals and for and while loops.
  • Create and call a method that takes parameters and returns a value.

Lesson

A program is a precise list of instructions. The robot does exactly what you write, in order, one line at a time, many times per second. It never guesses what you meant. That sounds strict, but it is also good news: when the robot does something strange, there is always a reason in the code, and you can find it. In FTC you will write programs in Java (with OnBot Java or Android Studio) or build the same ideas visually with Blocks. The concepts in this lesson are the same in all three.

Variables: named boxes for values

A variable is a named box that stores a value so you can use it later. In Java every variable has a type that says what kind of value it can hold. You create a variable by writing the type, a name, and usually a starting value. You can change the value later with =, which means 'store this value', not 'is equal to'.

TypeHoldsFTC example
intWhole numbersA motor port number, a counter, encoder ticks
doubleDecimal numbersMotor power from -1.0 to 1.0, a servo position, a joystick value
booleantrue or falseIs the claw open? Is a button pressed?
StringTextA message shown on the Driver Station
JAVA
1int loopCount = 0;              // whole number
2double drivePower = 0.5;        // decimal number
3boolean clawOpen = false;       // true or false
4String status = "Ready";        // text
5final double MAX_POWER = 0.8;   // final means it can never change
6
7loopCount = loopCount + 1;      // now 1
8drivePower = drivePower * 0.5;  // now 0.25
Declaring and updating variables

Conditionals: making decisions

A conditional lets the program choose what to do. An if statement checks a condition that is either true or false. If it is true, the code inside the braces runs; if not, Java checks the next else if, and finally runs the else part. You can combine conditions with && (and), || (or) and ! (not). Comparisons use >, <, >=, <=, == and !=.

JAVA
1double trigger = gamepad1.right_trigger;   // 0.0 (released) to 1.0 (fully pressed)
2
3if (trigger > 0.5) {
4    status = "Fast";
5} else if (trigger > 0.1) {
6    status = "Slow";
7} else {
8    status = "Stopped";
9}
10
11if (gamepad1.a && !clawOpen) {   // A is pressed AND the claw is not open
12    clawOpen = true;
13}
Choosing an action with if / else if / else

Loops: doing things again and again

A loop repeats code. A for loop is best when you know how many times to repeat. A while loop repeats as long as a condition stays true. Every TeleOp program you write this week is built around one big while loop: read the gamepad, set the motors, show telemetry, then do it all again, dozens of times per second. That is why the robot reacts instantly when the driver moves a stick.

JAVA
1// for loop: repeat a known number of times
2for (int i = 1; i <= 3; i++) {
3    telemetry.addData("Count", i);
4}
5
6// while loop: repeat while the condition is true
7while (opModeIsActive()) {
8    // read the gamepad, set motor powers, update telemetry
9}
A for loop and the while loop used in every TeleOp

Methods: naming a piece of work

A method is a named block of code you can run whenever you need it. It can take inputs called parameters and can send back a result with return. Methods keep programs short and readable: instead of copying the same five lines in three places, you write them once and call the method. You already use methods written by others: setPower, setPosition and telemetry.addData are all methods. The dot in leftFront.setPower(0.5) means 'call the setPower method of the leftFront object'. An object is a thing in code, such as a motor, that has its own data and methods.

JAVA
1// A method that returns a slower power when slow mode is on
2double scalePower(double power, boolean slowMode) {
3    if (slowMode) {
4        return power * 0.4;
5    }
6    return power;
7}
8
9// Calling the method
10double leftPower = scalePower(-gamepad1.left_stick_y, gamepad1.left_bumper);
Defining and calling a method with two parameters
  • Variables store values: pick the right type and a clear name.
  • Conditionals choose between actions with if, else if and else.
  • Loops repeat actions; your TeleOp runs inside while (opModeIsActive()).
  • Methods give a name to a piece of work so you can reuse it.

Key terms

Variable
A named storage location that holds a value of a specific type, which can change while the program runs.
Data type
The kind of value a variable can hold, such as int, double, boolean or String.
Conditional
A statement such as if/else that runs different code depending on whether a condition is true or false.
Loop
A structure such as for or while that repeats a block of code.
Method
A named, reusable block of code that can take parameters and return a result.
Object
A thing in code, such as a motor, that bundles its own data with methods you call using a dot.

Practical exercise

Paper Robot: trace the code

  1. 1In pairs, write the variables from the first code example on paper as labelled boxes with their starting values.
  2. 2Run the code by hand line by line and cross out and update each box when its value changes.
  3. 3Trace the trigger example three times, with right_trigger equal to 0.05, 0.3 and 0.9, and write the final value of status each time.
  4. 4Write your own method double clampPower(double power) that returns 1.0 if power is above 1.0, -1.0 if below -1.0, and power otherwise.
  5. 5Swap methods with another pair and test each other's method by hand with the inputs 1.7, -0.2 and -3.
Deliverable: A page showing your traced variable boxes, the three status results, and your clampPower method with the results of the three test inputs.

Knowledge check

Answer every question, then check your answers.

  1. Q1Which type should you use to store a motor power such as 0.75?
  2. Q2What is the difference between = and == in Java?
  3. Q3Why should the main loop of a TeleOp be while (opModeIsActive()) instead of while (true)?
  4. Q4In leftFront.setPower(0.5), what is setPower?

Further resources

Mark lesson complete