if... else... if

The ‘if‘ statement is pretty useful. It allows you to execute a block of code only if a certain condition is true. Here is an example:

public class MyClass {

  public static void main(String[] args) {
    
    int i = 3;

    if(i > 1) {
      System.out.println("GameCodePlus rules!");
    }
    
  }
}

In this example I declared an int variable and assigned it the value of 3. Then we come to the if statement. Java evaluates what is inside the ( ) curved brackets. I have (i > 1) and since i has a value of 3 that evaluates to true.

Because the if statement was true, Java then proceeds to execute the code contained within the { } curly brackets. And the output is:

GameCodePlus rules!

But what if the if statement had evaluated to false? Then Java would just move on down skipping over the code contained in the { } curly brackets. And this is where we could use an else statement.

An else statement will only execute if the preceding if statement is false.

public class MyClass {

  public static void main(String[] args) {

    int i = 3;

    if(i > 5) {
      System.out.println("GameCodePlus rules!");
    } else {
    System.out.println("Sorry, but GameCodePlus does not rule anything.");
    }
  }
}

What a stinky bit code that was… Luckily we can fix it with an else if statement.

The else if statement lets you apply another conditional check should the first if statement be false.

public class MyClass {

  public static void main(String[] args) {
    
    int i = 3;

    if(i > 5) {
      System.out.println("GameCodePlus rules!");
    } else if(i < 10) {
      System.out.println("GameCodePlus still rules!");
    } else {
      System.out.println("Sorry, but GameCodePlus does not rule anything.");
    }
    
  }
}

You could if you wanted, chain many more if and else if statements together. But too much of that will make your code look as if I wrote it.

Next Topic: Loops

Comments

Popular Posts