Using if ... else

On the previous page, we looked at the Java if statement, which can be used to make a "decision" in our program, executing a block of code if and only if a particular condition is true. But what if it isn't true?

In this case, we can use the else keyword to define another block of code to be run if the condition isn't true. The general pattern is:

if (condition) {
  ... code to run if condition true ...
} else {
  ... code to run if condition false ...
}

For example, in our program to print out all times tables except the 10 times table, we could write the following, which will print out a message telling the user why the 10 times table isn't being printed:

if (timesTableNo != 10) {
  System.out.println("The " + timesTableNo + " times table:");
  for (int n = 1; n <= 12; n++) {
    int result = n * timesTableNo;
    System.out.println(timesTableNo + " times " + n + " = " + n);
  }
} else {
  System.out.println("Not printing " + timesTableNo +
    " times table because it's easy!");
}

Notice that we could equally have written the above code the other way round, as follows:

if (timesTableNo == 10) {
  System.out.println("Not printing " + timesTableNo +
    " times table because it's easy!");
} else {
  ... print times table ...
}

Deciding which way round to write things is sometimes a question of preference, or deciding which way round best reflects our "thought process". In this case, I would prefer the first way round, because the thing we basically want our program to do is "print all the times tables except 10". It arguably helps us to read our program if we put the "thing that we basically want to do" inside the main condition.

Next: combining conditions

On the next page, we look at how to combine several conditions using what are sometimes called logical operators.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.