Decision Making: Equality and Relational Operators

Một phần của tài liệu java for programmeras 2nd edition (Trang 68 - 71)

1. Multiplication, division and remainder operations are applied first. If an expres- sion contains several such operations, they’re applied from left to right. Multipli- cation, division and remainder operators have the same level of precedence.

2. Addition and subtraction operations are applied next. If an expression contains several such operations, the operators are applied from left to right. Addition and subtraction operators have the same level of precedence.

These rules enable Java to apply operators in the correct order.1When we say that operators are applied from left to right, we’re referring to theirassociativity. Some opera- tors associate from right to left. Figure 2.9 summarizes these rules of operator precedence.

A complete precedence chart is included in Appendix A.

2.7 Decision Making: Equality and Relational Operators

Aconditionis an expression that can betrueorfalse. This section introduces Java’sif selection statement, which allows a program to make adecisionbased on a condition’s value. For example, the condition “grade is greater than or equal to 60” determines wheth- er a student passed a test. If the condition in anifstatement is true, the body of theif statement executes. If the condition is false, the body does not execute. We’ll see an exam- ple shortly.

Conditions inifstatements can be formed by using theequality operators(==and

!=) andrelational operators(>,<,>=and<=) summarized in Fig. 2.10. Both equality oper- ators have the same level of precedence, which islowerthan that of the relational operators.

The equality operators associate from left to right. The relational operators all have the same level of precedence and also associate from left to right.

Figure 2.11 uses sixifstatements to compare two integers input by the user. If the condition in any of theseifstatements is true, the statement associated with thatifstate- ment executes; otherwise, the statement is skipped. We use aScannerto input the integers from the user and store them in variablesnumber1andnumber2. The program compares the numbers and displays the results of the comparisons that are true.

1. We use simple examples to explain the order of evaluation of expressions. Subtle issues occur in the more complex expressions you’ll encounter later in the book. For more information on order of eval- uation, see Chapter 15 ofThe Java™ Language Specification(java.sun.com/docs/books/jls/).

Operator(s) Operation(s) Order of evaluation (precedence)

* /

%

Multiplication Division Remainder

Evaluated first. If there are several operators of this type, they’re evaluated from left to right.

+ -

Addition Subtraction

Evaluated next. If there are several operators of this type, they’re evaluated from left to right.

= Assignment Evaluated last.

Fig. 2.9 | Precedence of arithmetic operators.

36 Chapter 2 Introduction to Java Applications

Standard algebraic equality or relational operator

Java equality or relational operator

Sample Java condition

Meaning of Java condition

Equality operators

= == x == y xis equal toy

≠ != x != y xis not equal toy

Relational operators

> > x > y xis greater thany

< < x < y xis less thany

≥ >= x >= y xis greater than or equal toy

≤ <= x <= y xis less than or equal toy Fig. 2.10 | Equality and relational operators.

1 // Fig. 2.11: Comparison.java

2 // Compare integers using if statements, relational operators 3 // and equality operators.

4 import java.util.Scanner; // program uses class Scanner 5

6 public class Comparison 7 {

8 // main method begins execution of Java application 9 public static void main( String[] args )

10 {

11 // create Scanner to obtain input from command line 12 Scanner input = new Scanner( System.in );

13

14 int number1; // first number to compare 15 int number2; // second number to compare 16

17 System.out.print( "Enter first integer: " ); // prompt 18 number1 = input.nextInt(); // read first number from user 19

20 System.out.print( "Enter second integer: " ); // prompt 21 number2 = input.nextInt(); // read second number from user 22

23 24 25 26 27 28 29 30 31

Fig. 2.11 | Compare integers usingifstatements, relational operators and equality operators.

(Part 1 of 2.)

if ( number1 == number2 )

System.out.printf( "%d == %d\n", number1, number2 );

if ( number1 != number2 )

System.out.printf( "%d != %d\n", number1, number2 );

if ( number1 < number2 )

System.out.printf( "%d < %d\n", number1, number2 );

2.7 Decision Making: Equality and Relational Operators 37

The declaration of classComparisonbegins at line 6. The class’smainmethod (lines 9–40) begins the execution of the program. Line 12 declaresScannervariableinputand assigns it aScannerthat inputs data from the standard input (i.e., the keyboard).

Lines 14–15 declare theintvariables used to store the values input from the user.

Lines 17–18 prompt the user to enter the first integer and input the value, respectively.

The input value is stored in variablenumber1.

Lines 20–21 prompt the user to enter the second integer and input the value, respec- tively. The input value is stored in variablenumber2.

Lines 23–24 compare the values of number1 and number2 to determine whether they’re equal. Anifstatement always begins with keywordif, followed by a condition in parentheses. Anifstatement expects one statement in its body, but may contain multiple statements if they’re enclosed in a set of braces ({}). The indentation of the body statement shown here is not required, but it improves the program’s readability by emphasizing that the statement in line 24is part oftheifstatement that begins at line 23. Line 24 executes only if the numbers stored in variablesnumber1andnumber2are equal (i.e., the condition is true). The ifstatements in lines 26–27, 29–30, 32–33, 35–36 and 38–39 compare 32

33 34 35 36 37 38 39

40 } // end method main 41 } // end class Comparison

Enter first integer: 777 Enter second integer: 777 777 == 777

777 <= 777 777 >= 777

Enter first integer: 1000 Enter second integer: 2000 1000 != 2000

1000 < 2000 1000 <= 2000

Enter first integer: 2000 Enter second integer: 1000 2000 != 1000

2000 > 1000 2000 >= 1000

Fig. 2.11 | Compare integers usingifstatements, relational operators and equality operators.

(Part 2 of 2.)

if ( number1 > number2 )

System.out.printf( "%d > %d\n", number1, number2 );

if ( number1 <= number2 )

System.out.printf( "%d <= %d\n", number1, number2 );

if ( number1 >= number2 )

System.out.printf( "%d >= %d\n", number1, number2 );

38 Chapter 2 Introduction to Java Applications

number1andnumber2using the operators!=,<,>,<=and>=, respectively. If the condition in one or more of theifstatements is true, the corresponding body statement executes.

There’s no semicolon (;) at the end of the first line of eachifstatement. Such a semi- colon would result in a logic error at execution time. For example,

would actually be interpreted by Java as

where the semicolon on the line by itself—called theempty statement—is the statement to execute if the condition in theifstatement is true. When the empty statement executes, no task is performed. The program then continues with the output statement, which al- ways executes, regardless of whether the condition is true or false, because the output state- ment is not part of theifstatement.

Figure 2.12 shows the operators discussed so far in decreasing order of precedence. All but the assignment operator,=, associate from left to right. The assignment operator,=, asso- ciates from right to left, so an expression likex = y = 0is evaluated as if it had been written asx = (y = 0), which first assigns the value0to variabley, then assigns the result of that assignment,0, tox.

Một phần của tài liệu java for programmeras 2nd edition (Trang 68 - 71)

Tải bản đầy đủ (PDF)

(1.164 trang)