if Statements

If you want to test a condition in a Java program, the most basic way is with an if statement. As you learned previously, the boolean variable type is used to store only two possible values: true or false. The if statement works along the same lines, testing to see whether a condition is true or false, and taking action only if the condition is true. You use if along with a condition to test, as in the following statement:

if (account < 0)
 System.out.println("Hear that bouncing noise? It's your checks");


Although this code is listed on two lines, it's one statement. The first part uses if to determine whether the account variable is less than 0 by using the < operator. The second part displays the text Hear that bouncing noise? It's your checks. The second part of an if statement will be run only if the first part is true. In the preceding example, if the account variable has a value of 0 or higher, the println statement will be ignored. Note that the condition you test with an if statement must be surrounded by parentheses, as in (account < 0).

By the Way

If you're not sure why if (account < 0) is not a statement, note that there is no semicolon at the end of the line. In Java programs, semicolons are used to show where one statement ends and the next one begins. In the preceding example, the semicolon does not appear until after the println portion of the statement. If you put a semicolon after the if portion, as in if (account < 0.01), you'll cause a logic error in your program that can be hard to spot. Take care regarding semicolons when you start using the if statement.


The less-than operator, <, is one of several different operators you can use with conditional statements. You'll become more familiar with the if statement as you use it with some of the other operators.

Less Than and Greater Than Comparisons

In the preceding section, the < operator is used the same way it was used in math class: as a less-than sign. There is also a greater-than conditional operator: >. This operator is used in the following statements:

if (elephantWeight > 780)
 System.out.println("Elephant too fat for tightrope act.");
if (elephantTotal > 12)
 cleaningExpense = cleaningExpense + 150;


The first if statement tests whether the value of the elephantWeight variable is greater than 780. The second if statement tests whether the elephantTotal variable is greater than 12. One thing to understand about if statements is that they often cause nothing to happen in your programs. If the two preceding statements are used in a program where elephantWeight is equal to 600 and elephantTotal is equal to 10, the rest of the if statements will be ignored. There will be times when you want to determine whether something is less than or equal to something else. You can do this with the <= operator, as you might expect; use the >= operator for greater-than-or-equal-to tests. Here's an example:

if (account <= 0)
 System.out.println("Hear that bouncing noise? It's your checks");


This version of the checkbook example tests whether account is less than or equal to the value 0, and taunts the user if it is.

Equal and Not Equal Comparisons

Another condition to check in a program is equality. Is a variable equal to a specific value? Is one variable equal to the value of another? These questions can be answered with the == operator, as in the following statements:

if (answer == rightAnswer)
 studentGrade = studentGrade + 10;
if (studentGrade == 100)
 System.out.println("Such a show off!");


Watch Out!

The operator used to conduct equality tests has two equal signs: ==. It's very easy to confuse this operator with the = operator, which is used to give a value to a variable. Always use two equal signs in a conditional statement.


You can also test inequality—whether something is not equal to something else. This is accomplished with the != operator, as shown in the following example:

if (answer != rightAnswer)
 score = score - 5;


You can use the == and != operators reliably with every type of variable except one: strings. To see whether one string has the value of another, use the equals() method described during Hour 6, "Using Strings to Communicate."

Organizing a Program with Block Statements

Up to this point, all of the if statements have been followed with a single instruction, such as the println() method. In many cases, you will want to perform more than one action in response to an if statement. To do this, you'll use the { and } characters to create a block statement. I believe the technical term for these characters is "squiggly bracket marks." Block statements are statements that are organized into a group. Previously, you have seen how block statements are used to mark the beginning and end of the main() block of a Java program. Each statement within the main() block is handled when the program is run. Listing 7.1 is an example of a Java program with a block statement used to denote the main() block. The block statement begins with the opening bracket { on Line 2 and ends with the closing bracket } on Line 11. Load your word processor and enter the text of Listing 7.1 as a new file.

Listing 7.1. The Game Program
 1: class Game {
 2: public static void main(String[] arguments) {
 3: int total = 0;
 4: int score = 7;
 5: if (score == 7) {
 6: System.out.println("You score a touchdown!");
 7: }
 8: if (score == 3) {
 9: System.out.println("You kick a field goal!");
10: }
11: total = total + score;
12: System.out.println("Total score: " + total);
13: }


Save this file as Game.java and compile it. If you're using the JDK, you can compile it by typing the following command:

javac Game.java


When you run the program, the output should resemble Listing 7.2.

Listing 7.2. The Output of the Game Program
You score a touchdown!
Total score: 7


You also can use block statements in conjunction with if statements to make the computer do more than one thing if a conditional statement is true. The following is an example of an if statement that includes a block statement:

if (playerScore > 9999) {
 playerLives++;
 System.out.println("Extra life!");
 difficultyLevel = difficultyLevel + 5;
}


The brackets are used to group all statements that are part of the if statement. If the variable playerScore is greater than 9,999, three things will happen:

  • The value of the playerLives variable increases by one (because the increment operator ++ is used).
  • The text ExTRa life! is displayed.
  • The value of the difficultyLevel variable is increased by 5.

If the variable playerScore is not greater than 9,999, nothing will happen. All three statements inside the if statement block will be ignored.

      
Comments