Programs need to be able to react differently to varying data. Conditional statements let us do this. For example, a robot must be able to monitor its sensors to prevent collisions. Consider (and try running) the following program:

  1. Create a new folder in your Java Projects folder named Conditional Example
  2. Create a new file (New->File)
  3. Cut and paste this program into the file.
    public class ConditionalExample {
        public static void main(String args[]) {
            int rangeInInches;
            rangeInInches = 10;
            if (rangeInInches < 20) {
               System.out.println("stop motors so we don't crash!");
            } else {
               System.out.println("full speed ahead!");
  4. Save the program as (notice how the name of the file must match the name of the class)

Running the program

Run the program using the debugger with a breakpoint set on the first executable line (rangeInInches=10);

  • Step through the program using the stepover tool and observe the flow of the program.
  • Restart the program using the restart tool
  • Change the values stored in the variable rangeInInches to 25 and observe the flow of the program.

Understanding the program

In the example above, we

  1. Create a variable named rangeInInches. Notice how the name of the variable conveys information about what type of information can be held in it including the units; this is a very good programming practice and will make your programs more readable.
  2. Store a value (10) in the variable rangeInInches.
    In a robot program, we might get the value from a distance measurement sensor.
  3. Compare the value to 20
    1. If the value is less than 20, we display the message stop motors so we don't crash''.
      In a robot program, we would actually stop the motors
    2. If the value is not less than 20, we display the message full speed ahead''

Java allows you to have multiple conditionals using the syntax:

     if (<condition 1>) {
        // do this if condition 1 is true
        // also do this if condition 1 is true
     } else if (<condition 2>) {
        // do this if condition 1 was not true but condition 2 is true
     } else {
        // do this if neither condition 1 nor condition 2 were true

You can have as many else if clauses as you wish.

Some things to note:

  • The conditions are always placed within parentheses
  • The conditions are logic statements that must evaluate to true or false (e.g. (a < 10))
  • The conditions are evaluated in order and the first condition that matches is executed, the rest are skipped
  • The else if and else clauses are optional

Extra Credit

  • Try adding an else if clause to the sample program:
  • Read more about Java conditionals here
Last modified 3 years ago Last modified on Nov 4, 2019, 3:28:03 PM