If/Else and If/Else If/Else Statements

If/Else Statements


There are times when we want our program to perform a “decision” and execute different code accordingly. For example, say we want to determine if a number is even or odd. We know that if a number is divisible by 2, with no remainder, that the number is even, otherwise it is odd. That is a simple If/Else statement: if the number is divisible by 2 it is even, else the number is odd. We are going to look at an example code now.


In Java, the % operator represents remainder division, that is it gives the remainder of the division, so 5 % 2 would be 1. The / operator is integer division, 5 / 2 is 2. If you want your answer to be in decimal form, one of the numbers needs to be of the double type, 5.0 / 2 is 2.5 (as well as 5 / 2.0).

The following program may be different than some you have seen, especially if you have only been working through the IntelliBrain tutorials on this site. This program is designed to run on the console and the results will be displayed in the output window of your IDE. The import statement on line 5 brings in all the libraries needed to allow us to use the keyboard to interact with the program. Line 11 will have the program display the message "Please enter an integer number:" within the IDE output display window as a prompt for you to use the keyboard and enter a number. Line 13 and 15 are what we need to use the keyboard and store the number you enter into a variable named num. Now that we have a number, we can proceed with our program.


/**

 *Even/Odd If/Else Statement Example

 */



import java.util.Scanner;



public class IfElse {



    public static void main(String[] args) {

        

        System.out.println("Please enter an integer number:");

        

        Scanner input = new Scanner(System.in);

        

        int num = input.nextInt();

        

        if(num % 2 == 0)  //the parentheses contains a boolean expression, it can be true or false



            System.out.println("Your number is even.");

        

        else



            System.out.println("Your number is odd.");

        

    }

}

Pretty simple right? The key is the boolean expression (located on line 17, with the comment). When the program reaches the if, it then reads inside the parentheses and evaluates whether that expression is true or if it is false. If it is true, the program then executes the code in the block immediately following the if, otherwise (else) it skips that block of code and executes the code in the block following the else.


More If/Else Statements


  1. Why do you think being able to have the program perform a decision is helpful?

  2. Can you think of another situation where using an if/else statement would be beneficial?

  3. How would you write the code for the situation you just described? Go ahead and try it!


But what about if you have situation where you have three choices? Or 4? Or more? In these cases we can expand the if/else statements to accommodate as many conditions as we have by modifying the form slightly. Head on to the next section to learn more.


If/Else If/Else Statements


If/Else statements can be expanded to handle more than two possibilities. This is possible because the program executes code line by line. The program will look at the first case and if it is not true it skips the associated code in the following block and moves on to the next true/false condition. This process continues until it executes a block of code, or it reaches the else statement - and then it will execute that block. Consider the following code which will assign a letter grade to a number using a congenital grading scale:



/**

 *Grade If/Else Statement Example

 */



import java.util.Scanner;



public class IfElse {



    public static void main(String[] args) {

        

        System.out.println("Please enter your grade:");

        

        Scanner input = new Scanner(System.in);

        

        int grade = input.nextInt();

        

        if(grade >= 90)

            System.out.println("Your grade is an A.");

        

        else if(grade >= 80)

            System.out.println("Your grade is a B.");

        

        else if(grade >= 70)

            System.out.println("Your grade is a C.");

        

        else if(grade >= 60)

            System.out.println("Your grade is a D.");

        

        else

            System.out.println("Your grade is a F."); 

    }

}

Go ahead and try it out! Run the program and input a few different grades which span the range and see what the results are.


More on If/Else If/Else Statements


  1. Can you interchange an if/else statement with an if/else if/else statement? Why or why not?

  2. Can you think of another situation where you would want to use an if/else if/else statement?

  3. How would you write the code for the situation you just described? Go ahead and try it!


If you have more than one statement per if else/if else you need to put a { after the (true/false) and a } before the next else/if or else statement. You only get to use the shortcut of not putting the braces in ONLY IF a one line statement follows!! To avoid possible mistakes though, it is good to go ahead and use the braces even if you only have a one line statement.