IF/ELSE/ELSE IF
Subscribe to Tech with Tim
The If Statement
An if statement is something that allows for us to execute a certain block of code IF a certain condition true. We denote the start of an if statement by typing the keyword if and then enclosing a condition within (). Then proceeding the brackets we enclose the code that we want to run inside {}.
if (condition){ code goes in here }
public class Main { public static void main(String[] args){ int x = 5; if (x == 5){ System.out.println("The variable x is 5"); // This will be printed } if (x == 6){ System.out.println("The variable x is 6"); // This will not be printed } } }
The Else Statement
The else statement is an optional statement whose code will be executed if the if statement above it did not run. This means if we decide to create an else statement it must come directly after an if statement. It CANNOT stand alone.
public class Main { public static void main(String[] args){ int x = 5; if (x == 5){ System.out.println("The variable x is 5"); // This will be printed } else{ System.out.println("X is NOT equal to 5"); //This will run only if x is not 5 } // In any case only one message will every be printed to the screen } }
The Else If Statement
The else if statement is exactly what it sounds like. A combination between the else and the if. Like the else statement it is optional but if we choose to use it must come after an if and before a possible else. The else if's condition to run will only be checked if the if statement above it did not run. We can use unlimited else if's but can only have one if and one else in each statement block.
public class Main { public static void main(String[] args){ int x = 8; if (x < 5 ){ System.out.println("The variable x is less than 5"); // This will be executed if } else if (x < 7){ System.out.println("1st else if ran"); // This will be executed if x >= 5 and x < 7 } else if (x < 10){ System.out.println("2nd else if ran"); // This will run if x is between 7 and 10 } else{ System.out.println("Else ran"); //This will be executed if all of statements above did not run } // In any case only one message will every be printed to the screen } }