if Statements

The most basic way to test a condition in Java is by using an if statement. The if statement tests whether a condition is true or false and takes action only if the condition is true.

You use if along with the condition to test, as in the following statement:

if (account < 0) {
    System.out.println("Account overdrawn; you need a bailout");
}

The if statement checks whether the account variable is below 0 by using the less than operator <. If it is, the block within the if statement is run, displaying text.

The block only runs if the condition is true. In the preceding example, if the account variable has a value of 0 or higher, the println statement is ignored. Note that the condition you test must be surrounded by parentheses, as in (account < 0).

The less-than operator < is one of several different operators you can use with conditional statements.

Less Than and Greater Than Comparisons

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

int elephantWeight = 900;
int elephantTotal = 13;
int cleaningExpense = 200;

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.

If the two preceding statements are used in a program where elephantWeight is equal to 600 and elephantTotal is equal to 10, the statements within each if block are ignored.

You can determine whether something is less than or equal to something else with the <= operator. Here’s an example:

if (account <= 0) {
    System.out.println("You are flat broke");
}


Caution

The operator used to conduct equality tests has two equal signs: ==. It’s 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.


There’s also a >= operator for greater-than-or-equal-to tests.

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("Show off!");

}

You also can test inequality, whether something is not equal to something else, with the != operator, as follows:

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

You can use the == and != operators with every type of variable except for strings, because strings are objects.

Organizing a Program with Block Statements

Up to this point, the if statements in this hour have been accompanied by a block contained within the { and } brackets. (I believe the technical term for these characters is “squiggly bracket marks.”)

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.

An if statement does not require a block statement. It can occupy a single line, as in this example:

if (account <= 0) System.out.println("No more money");

The statement that follows the if conditional only is executed if the conditional is true.

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 13. Create a new empty Java file called Game in NetBeans and enter the text in Listing 7.1.

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:     }
14: }


When you run the program, the output should resemble Figure 7.1.

Figure 7.1. The output of the Game program.

Image

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

int playerScore = 12000;
int playerLives = 3;
int difficultyLevel = 10;

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 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 happens. All three statements inside the if statement block are ignored.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.122.244