The flow chart of the preceding statement is shown in Figure 3.3(b). If the value of radius is greater than or equal to 0, then the area is computed and the result is displayed; otherwise , the two statements in the block will not be executed.

Note

The booleanExpression is enclosed in parentheses for all forms of the if statement. Thus, for example, the outer parentheses in the following if statements are required.

[Page 74]

The braces can be omitted if they enclose a single statement.

Caution

Forgetting the braces when they are needed for grouping multiple statements is a common programming error. If you modify the code by adding new statements in an if statement without braces, you will have to insert the braces if they are not already in place.

Adding a semicolon at the end of an if clause, as shown in (a) in the following code, is a common mistake.

This mistake is hard to find because it is neither a compilation error nor a runtime error, it is a logic error. The code in (a) is equivalent to (b) with an empty body.

This error often occurs when you use the next -line block style. Using the end-of-line block style will prevent this error.

3.3.2. if ... else Statements

A simple if statement takes an action if the specified condition is true . If the condition is false , nothing is done. But what if you want to take alternative actions when the condition is false ? You can use an if ... else statement. The actions that an if ... else statement specifies differ based on whether the condition is true or false .

If radius >= 0 is true , area is computed and displayed; if it is false , the message "Negative input" is printed.

As usual, the braces can be omitted if there is only one statement within them. The braces enclosing the System.out.println("Negative input") statement can therefore be omitted in the preceding example.

Using the if else statement, you can rewrite the code for determining whether a number is even or odd in the preceding section, as follows :

This is more efficient because whether number % 2 is is tested only once.

[Page 76]

3.3.3. Nested if Statements

The statement in an if or if ... else statement can be any legal Java statement, including another if or if ... else statement. The inner if statement is said to be nested inside the outer if statement. The inner if statement can contain another if statement; in fact, there is no limit to the depth of the nesting. For example, the following is a nested if statement:

if (i > k) { if (j > k) System.out.println( "i and j are greater than k" ); } else System.out.println( "i is less than or equal to k" );

The if (j > k) statement is nested inside the if (i > k) statement.

The nested if statement can be used to implement multiple alternatives. The statement given in Figure 3.5(a), for instance, assigns a letter grade to the variable grade according to the score, with multiple alternatives.

Figure 3.5. A preferred format for multiple alternative if statements is shown in (b).

The execution of this if statement proceeds as follows. The first condition (score >= 90.0) is tested. If it is true , the grade becomes 'A' . If it is false , the second condition (score >= 80.0) is tested. If the second condition is true , the grade becomes 'B' . If that condition is false , the third condition and the rest of the conditions (if necessary) continue to be tested until a condition is met or all of the conditions prove to be false . If all of the conditions are false , the grade becomes 'F' . Note that a condition is tested only when all of the conditions that come before it are false .

The if statement in Figure 3.5(a) is equivalent to the if statement in Figure 3.5(b). In fact, Figure 3.5(b) is the preferred writing style for multiple alternative if statements. This style avoids deep indentation and makes the program easy to read.

Note

The else clause matches the most recent unmatched if clause in the same block. For example, the following statement in (a) is equivalent to the statement in (b).

The compiler ignores indentation. Nothing is printed from the statements in (a) and (b). To force the else clause to match the first if clause, you must add a pair of braces:

Often new programmers write the code that assigns a test condition to a boolean variable like the code in (a):

The code can be simplified by assigning the test value directly to the variable, as shown in (b).

Caution

To test whether a boolean variable is true or false in a test condition, it is redundant to use the equality comparison operator like the code in (a):

Instead, it is better to use the boolean variable directly, as shown in (b). Another good reason to use the boolean variable directly is to avoid errors that are difficult to detect. Using the operator instead of the == operator to compare equality of two items in a test condition is a common error. It could lead to the following erroneous statement:

if (even = true ) System.out.println( "It is even." );

This statement does not have syntax errors. It assigns true to even so that even is always true .

[Page 78]

Tip

If you use an IDE such as JBuilder, NetBeans, or Eclipse, please refer to Learning Java Effectively with JBuilder/NetBeans/Eclipse in the supplements. This supplement shows you how to use a debugger to trace a simple if-else statement.

3.3.4. Example: Computing Taxes

This section uses nested if statements to write a program to compute personal income tax. The United States federal personal income tax is calculated based on filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. The tax rates for 2002 are shown in Table 3.7. If you are, say, single with a taxable income of $10,000, the first $6,000 is taxed at 10% and the other $4,000 is taxed at 15%. So your tax is $1,200.

Table 3.7. 2002 U.S. Federal Personal Tax Rates

Tax rate

Single filers

Married filing jointly or qualifying widow/widower

Married filing separately

Head of household

10%

Up to $6,000

Up to $12,000

Up to $6,000

Up to $10,000

15%

$6,001 “$27,950

$12,001 “$46,700

$6,001 “$23,350

$10,001 “$37,450

27%

$27,951 “$67,700

$46,701 “$112,850

$23,351 “$56,425

$37,451 “$96,700

30%

$67,701 “$141,250

$112,851 “$171,950

$56,426 “$85,975

$96,701 “$156,600

35%

$141,251 “$307,050

$171,951 “$307,050

$85,976 “$153,525

$156,601 “$307,050

38.6%

$307,051 or more

$307,051 or more

$153,526 or more

$307,051 or more

Your program should prompt the user to enter the filing status and taxable income and computes the tax for the year 2002. Enter 0 for single filers, 1 for married filing jointly, 2 for married filing separately, and 3 for head of household. A sample run of the program is shown in Figure 3.6.

Figure 3.6. The program computes the tax using if statements.

Your program computes the tax for the taxable income based on the filing status. The filing status can be determined using if statements outlined as follows:

For each filing status, there are six tax rates. Each rate is applied to a certain amount of taxable income. For example, of a taxable income of $400,000 for single filers, $6,000 is taxed at 10%, (27950 “ 6000) at 15%, (67700 “ 27950) at 27%, (141250 “ 67700) at 35%, and (400000 “ 307050) at 38.6%.

Listing 3.4 gives the solution to compute taxes for single filers. The complete solution is left as an exercise.

The import statement (line 1) makes the class javax.swing.JOptionPane available for use in this example.

The program receives the filing status and taxable income. The multiple alternative if statements (lines 22, 42, 45, 48, 51) check the filing status and compute the tax based on the filing status.

Like the showMessageDialog method, System.exit(0) (line 53) is also a static method. This method is defined in the System class. Invoking this method terminates the program. The argument indicates that the program is terminated normally.

Note

An initial value of is assigned to tax (line 20). A syntax error would occur if it had no initial value because all of the other statements that assign values to tax are within the if statement. The compiler thinks that these statements may not be executed and therefore reports a syntax error.

3.3.5. Example: An Improved Math Learning Tool

This example creates a program for a first grader to practice subtraction. The program randomly generates two single-digit integers number1 and number2 with number1 > number2 and displays a question such as "What is 9-2?" to the student, as shown in Figure 3.7(a). After the student types the answer in the input dialog box, the program displays a message dialog box to indicate whether the answer is correct, as shown in Figure 3.7(b).

Figure 3.7. The program generates a subtraction question and grades the student's answer.

To generate a random number, use the random() method in the Math class. Invoking this method returns a random double value d such that 0.0 d < 1.0 So (int)(Math.random() *10) returns a random single-digit integer (i.e., a number between and 9 ).

To swap two variables number1 and number2 , a temporary variable temp (line 11) is used to first hold the value in number1 . The value in number2 is assigned to number1 (line 12), and the value in temp is assigned to number2 .