Hour 7. Using Conditional Tests to Make Decisions

Writing a computer program has been compared to telling a household robot what to do. You provide the computer a list of instructions, called statements, and these instructions are followed to the letter. You can tell the computer to work out some unpleasant mathematical formulas, and it will work them out for you. Tell it to display some information, and it will dutifully respond. However, there are times when you need the computer to be more selective about what it does. For example, if you have written a program to balance your checkbook, you might want the computer to display a warning message if your account is overdrawn. The warning could be something along the lines of "Hear that bouncing noise? It's your checks." The computer should display this message only if your account is overdrawn. If it isn't, the message would be both inaccurate and emotionally upsetting. The way to accomplish this task in a Java program is to use a statement called a conditional. Conditionals cause something to happen in a program only if a specific condition is met. During this hour, you'll learn how to use three different types of conditional statements: if, else, and switch. The following topics will be covered:

  • Testing to see whether conditions are met
  • Using the if statement for basic conditional tests
  • Using other statements in conjunction with if
  • Testing whether one value is greater than or less than another
  • Testing whether two values are equal or unequal
  • Using else statements as the opposite of if statements
  • Chaining several conditional tests together
  • Using the switch statement for complicated conditional tests
  • Creating complicated tests with the ternary operator