Decisions & Loops 🔁
beginner25 XP

Robot Decisions with if

Use sensors and if/else to stop before hitting a wall.

Robot Decisions with if 🚦

Robots read sensors and decide what to do. In Java, decisions use if and else:

Java
public class Main {
    public static void main(String[] args) {
        int distance = 12; // centimeters to the wall

        if (distance < 20) {
            System.out.println("STOP! Wall ahead!");
        } else {
            System.out.println("Full speed ahead!");
        }
    }
}
  • The check goes in round brackets ( ).
  • What to do goes in curly braces { }.
  • else runs when the check is false.

Comparing

SymbolMeans
< / >less than / greater than
<= / >=less or equal / greater or equal
==is equal to (two =!)
!=is not equal to

More choices: else if

Java
public class Main {
    public static void main(String[] args) {
        int temperature = 34;

        if (temperature > 30) {
            System.out.println("Greenhouse: open the windows");
        } else if (temperature < 10) {
            System.out.println("Greenhouse: turn on the heater");
        } else {
            System.out.println("Greenhouse: just right");
        }
    }
}

Java checks from top to bottom and runs only the first match.

Two checks at once: && and ||

  • && means and: both must be true.
  • || means or: at least one must be true.
Java
public class Main {
    public static void main(String[] args) {
        int battery = 60;
        boolean clearPath = true;
        if (battery > 20 && clearPath) {
            System.out.println("Mission go!");
        }
    }
}

🛰️ Fun fact

Self-driving cars and Mars rovers make thousands of if-style decisions every second, using cameras and sensors to decide when to stop, turn or go.

☕

Want to run it yourself?

Predict what the code prints first, then check! Copy an example above, paste it into the free online Java editor, and press Run. Keep the first line as public class Main.

Open the online Java editor ↗

Opens Programiz, a free site that isn't run by First Coding Path and may show ads. Grown-ups, you might like to take a look first.

Quick check

01/6
int distance = 50; if (distance < 20) {...print "STOP"...} else {...print "GO"...}. What prints?