Skip to the content.
3.1: Boolean Expressions 3.2: If Control Flow 3.3: If Else 3.4: Else If 3.5: Compound Booleans 3.6: Equivalent Booleans 3.7: Comparing Objects 3.8: Homework

Unit 3 Team Teach - 3.3

Unit 3 Team Teach

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) {

    console.log("x is greater than 10");
    console.log("This code when the condition is true");
    } else {
    
    console.log("x is 10 or less");
    console.log("This code runs when the condition is false");
}
//    Without brackets:
        
   console.log("x is greater than 10");
   console.log("this code will always run");
|       console.log("x is greater than 10");

cannot find symbol

  symbol:   variable console



|       console.log("This code when the condition is true");

cannot find symbol

  symbol:   variable console



|       console.log("x is 10 or less");

cannot find symbol

  symbol:   variable console



|       console.log("This code runs when the condition is false");

cannot find symbol

  symbol:   variable console

image

  1. Based on this code, if you were younger than 16 what would it print out?
    • If you were less than 16 years, it will print that you are not old enough for a license.
  2. Write your own if else statement
public static void main(String[] args) {
    int myAge = 18;
    System.out.println("Current age: " + myAge);
    
    if (myAge >= 18) {
        System.out.println("You can vote this year.");
    }
}