3.3 If Else Statements

Purpose of Else Statements

Else statements: Handles what happens when the if condition is false. Structure of If-Else:

  • If statement with a condition.
  • Else statement without a condition.
  • Both parts have code blocks surrounded by {}.

don’t forget the brackets

int x = 20;
if (x > 10) {
    System.out.println("x is greater than 10");
    System.out.println("This code runs when the condition is true");
} else {
    System.out.println("x is 10 or less");
    System.out.println("This code runs when the condition is false");
}

x is greater than 10
This code runs when the condition is true

image

  1. Based on this code, if you were younger than 16 what would it print out?
  2. Write your own if else statement
int myAge = 15;
if (myAge >= 16) {
    System.out.println("You can start learning to drive!");
} else {
    System.out.println("You cannot learn to drive yet.");
}
You cannot learn to drive yet.
public static void main(String[] args) {
    int age = 18;

    if (age >= 18) {
        System.out.println("You are eligible to vote.");
    } else {
        System.out.println("You are not eligible to vote.");
    }
}
if (20 > 18) {
    System.out.println("20 is greater than 18");
  }
20 is greater than 18