Overview of This Lesson

In programming, we use If Statements to allow our programs to. make decisions. For example, a program might want to ask the user if they're sure they want to exit a program, and if the user says yes, the program terminates. Or a program might ask the user to enter a user name to view their order history. If the user name is valid, the order entry screen is displayed. If the name is not valid, an error message appears.

If statements can be single-sided, double-sided, or can be multi-sided. We'll look at each of these and try some examples.

Pre-Requisites

Before doing this lesson, make sure you've gone through the relational and logical expressions tutorial.

Single-Sided Ifs

Single-sided ifs are used when you have an action you want to perform when a specific condition is true, but nothing to do when the condition is false.

A single sided If in Java has the general form:

if (relationalExpression) {
	// code to execute if relationalExpression
	// evaluates to true
}

The if-block (the code between the braces) only executes if the relational expression evaluates to true. If there is only one statement in the if-block, you can omit the braces. For example, this is perfectly valid:

if (x > 3)
	System.out.println("x is larger than 3");

However, this code below will not give the results you would expect:

if (x > 3)
	System.out.println("x is larger");
	System.out.println(" than 3);

In this example, the second print statement is not part of the if-block and will be executed regardless of whether or not x > 3 is true or false. To try this out, you can enter this code segment into a new program and declare/initialize the variable x to 5, then run the program. Then change x's value to 2 and run the program.

For beginning programmers, or programmers new to a Java style of syntax, I would get into the habit of leaving the braces on all the time until you become comfortable with leaving them off. As you'll see later on, leaving off the braces at the wrong time can cause some serious logic errors.

Exercises

1. Write a program that asks the user for a number less than 100. If the user's input is 100 or more, display a message on the console.

2. Modify the program: Instead of checking to see if the number is 100 or more, check to see if the number is less than 100. If it is, calculate the square root of the number, the square of the number, and the cube of the number. Then display these on the console.

1.

question 1 solution
Question 1. valid number version 1

2.

question 2 solution
Question 2. valid number version 2

Double-Sided Ifs

A double-sided if has two actions: one to perform if the condition is true, and one to perform if the condition is false. The general form of the double-sided If statement is:

if (relationalExpression) {
    // code to execute if relationalExpression
    // evaluates to true
} else {
    // code to execute if relationalExpression
    // evaluates to false
}

Note that we still only have one condition, but now we have two blocks of code. The if-block executes when the condition is true, and the else-block executes when the condition is false. Only one of the two blocks will execute!

As with the single-sided If, if you have only one code statement in either the if-block or the else-block, you can leave off the braces. For example, all of these are acceptable:

if (x > 3) 
    System.out.println("x is bigger than 3");
else
    System.out.println("x is 3 or less");
...
if (x > 3) {
    System.out.println("x is bigger");
    System.out.println(" than 3");
} else
    System.out.println("x is 3 or less");
...
if (x > 3)
    System.out.println("x is bigger than 3");
else {
    System.out.println("x is 3");
    System.out.println(" or less");
}

Exercises

Write programs for each of the following:

  1. Ask the user for a whole number. Display a message on the screen that indicates whether the number is even or odd.
  2. The method Math.random() generates a random double number greater than 0.0 and less than 1.0. Write a program that simulates flipping a coin. Call the Math.random() method and if the number generated is less than .5, display "HEADS". Otherwise, display "TAILS".
  3. Write a program that generates a random integer from 1 to 5. Then ask the user to guess that number. If they guess correctly, display the message, "You guessed correctly!". If they guess incorrectly, display the message, "Sorry, you guessed incorrectly."
  4. Write a program that simulates the tossing of two dice (generate two random integers from 1 to 6). If doubles are rolled, display a "You Win!!" message. Otherwise, tell the user what dice values they rolled.
  5. In a bank where you work, money is given an interest rate of 7.5% if it is left in an account for more than 5 years; otherwise, the interest rate is 4.5%. Write a program that asks the user for their current account balance, and number of years their money has been sitting in the account. Then assign the proper interest rate to a variable interestRate. Finally, calculate and display the total interest for the current year
  6. A program calculates a person's weekly pay based on the following: If the hours worked are less than or equal to 40, the person receives 10 dollars per hour; otherwise, the person receives 10 dollars for the first 40 hours and then 15 dollars for the hours they work over 40. Your program should ask for the number of hours from the user, and then calculate the weekly pay. Display your result.
  7. Write a program that checks for a valid department number entered by the user. A department number is valid if it is between 1 and 45, inclusive. Display messages stating whether or not the department number is valid.
  8. Modify the previous question: A valid department number is between 1 and 45 inclusive, or greater than 200.
  9. Modify the previous question: valid department numbers include department 50, those between 1 and 45 inclusive, and those that are greater than 200.

1.

solution #1
Question 1. number is even or odd

2.

solution #2
Question 2. simulate coin flip

3.

solution #3
Question 3. guess a number

4.

solution #4
Question 4. roll pair of dice

5.

solution #5
Question 5. determine interest rate

6.

solution #6
Question 6. calculate pay with overtime

7.

solution #7
Question 7. validate department # (a)

8.

solution #8
Question 8. validate department # (b)

9.

solution #9
Question 9. validate department # (c)

Multi-Sided Ifs

Multiple-Sided Ifs are a set of if and else blocks that check multiple conditions. For example, you might want to check a variable to see if it contained the number 1, the number 2, the number 3, or the number 4 and have a different action for each number. The multi-sided if will have four different conditions, and when it finds the one condition that is true, that block is executed.

The general form of a multi-sided if statement in Java is:

if (expression1) {
	// execute this if expression1 is true
} else if (expression2) {
	// execute this if expression2 is true
} else if (expression3) {
	// execute this if expression3 is true
} else if (expression4) {
	// execute this if expression4 is true
} else {
	// execute this if none of the above are true
}

Here's a concrete example you can try:

if (number == 1 || number == 2) {
  System.out.println("1, 2, Buckle my shoe");
} else if (number == 3 || number == 4) {
  System.out.println("3, 4, Close the door");
} else if (number == 5 || number == 6) {
  System.out.println("5, 6, Pick up sticks");
} else if (number == 7 || number == 8) {
  System.out.println("7, 8, Don't be late!");
} else {
  System.out.println("I don't know any more...");
}      

You can have as many relational expressions as you need in this kind of structure. Notice the single else-block at the bottom: this block is optional and can be used if you want code to execute when none of the conditions applies.

As with the other structures, you can eliminate the braces if there is only one statement in a block. For example, this is also valid:

if (number == 1 || number == 2) 
    System.out.println("1, 2, Buckle my shoe");
else if (number == 3 || number == 4) 
    System.out.println("3, 4, Close the door");
else if (number == 5 || number == 6) 
    System.out.println("5, 6, Pick up sticks");
else if (number == 7 || number == 8) 
    System.out.println("7, 8, Don't be late!");
else 
    System.out.println("I don't know any more...");
   

Exercises

  1. The following program determines and displays the letter grade for a student's final grade:
    import java.util.Scanner;
    
    public class GetLetterGrade {
    
        public static void main(String[] args) {
    
            Scanner keysIn = new Scanner(System.in);
            System.out.print("Enter the final grade: ");
            double grade = keysIn.nextDouble();
            String letter = "";
    
            if (grade < 50) {
                letter = "F";
            } else if (grade >= 50) {
                letter = "D";
            } else if (grade >= 60) {
                letter = "C";
            } else if (grade >= 65) {
                letter = "C+";
            } else if (grade >= 70) {
                letter = "B";
            } else if (grade >= 75) {
                letter = "B+";
            } else if (grade >= 80) {
                letter = "A";
            } else if (grade >= 90) {
                letter = "A+";
            }
    
            System.out.println("Letter grade: " + letter);
        }
    }
    1. What would the output be if the user entered a final grade of 48?
    2. What would the output be if the user entered a final grade of 55?
    3. What would the output be if the user entered a final grade of 85?
    4. Why doesn't this program do what it's supposed to do? How would you rewrite it correctly?
  2. 2. Write a Java program that calculates and displays the interest rate for funds that are left on deposit for a certain amount of time. The interest rate is determined by the following chart:
    Years on Deposit Rate
    5 years or more 4.75%
    4 years or more, but less than 5 years 4.5%
    3 years or more, but less than 4 years 4%
    2 years or more, but less than 3 years 3.5%
    1 year or more, but less than 2 years 3%
    less than 1 year 2.5%
  3. A program needs to display the amount of commission paid to sales people. Commission paid is equal to the amount of sales multiplied by the commission rate. Commission rates are assigned according to the following chart:
    Sales Amount Commission Rate
    under $1000 5%
    $1000 or more but less than $2000 7.5%
    $2000 or more, but less than $3500 10%
    $3500 or more 15%

1. a. What would the output be if the user entered a final grade of 48? F

1. b. What would the output be if the user entered a final grade of 55? D

1. c. What would the output be if the user entered a final grade of 85? D

1. d. Why doesn't this program do what it's supposed to do? How would you rewrite it correctly? It doesn't work because the range check is not done properly. Since you're starting from the bottom and going up to higher values, you should be comparing grade to the highest value in each range.

question 1 solutionRewrite grades program

Question 2:

question 2 solution
Question 2. determine interest

Question 3:

question 3 solution part 1
question 3 solution part 2
Question 3. calculate sales commission