Home > Articles > Programming > Java

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book

2.8 Decision Making: Equality and Relational Operators

A condition is an expression that can be true or false . This section introduces Java's if selection statement, which allows a program to make a decision based on a condition's value. For example, the condition "grade is greater than or equal to 60" determines whether a student passed a test. If the condition in an if statement is true, the body of the if statement executes. If the condition is false, the body does not execute. We'll see an example shortly.

Conditions in if statements can be formed by using the equality operators ( == and != ) and relational operators ( > , < , >= and <= ) summarized in Fig. 2.14. Both equality operators have the same level of precedence, which is lower than 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.

Fig 2.14. Equality and relational operators.

Standard algebraic equality or relational operator

Java equality or relational operator

Sample Java condition

Meaning of Java condition

Equality operators

=

==

x == y

x is equal to y

u2260.gif

!=

x != y

x is not equal to y

Relational operators

>

>

x > y

x is greater than y

<

<

x < y

x is less than y

u2265.gif

>=

x >= y

x is greater than or equal to y

u2264.gif

<=

x <= y

x is less than or equal to y

Figure 2.15 uses six if statements to compare two integers input by the user. If the condition in any of these if statements is true, the statement associated with that if statement executes; otherwise, the statement is skipped. We use a Scanner to input the integers from the user and store them in variables number1 and number2. The program compares the numbers and displays the results of the comparisons that are true.

Fig 2.15. Compare integers using if statements, relational operators and equality operators.

 1   // Fig. 2.15: 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         if ( number1 == number2 )                              
24            System.out.printf( "%d == %d\n", number1, number2 );
25
26         if ( number1 != number2 )                              
27            System.out.printf( "%d != %d\n", number1, number2 );
28
29         if ( number1 < number2 )                               
30            System.out.printf(  "%d < %d\n", number1, number2 );
31
32         if ( number1 > number2 )                               
33            System.out.printf(  "%d > %d\n", number1, number2 );
34
35         if ( number1 <= number2 )                              
36            System.out.printf( "%d <= %d\n", number1, number2 );
37
38         if ( number1 >= number2 )                              
39            System.out.printf( "%d >= %d\n", number1, number2 );
40      } // end method main
41   } // end class Comparison

The declaration of class Comparison begins at line 6

public class Comparison

The class's main method (lines 9–40) begins the execution of the program. Line 12

Scanner input = new Scanner( System.in );

declares Scanner variable input and assigns it a Scanner that inputs data from the standard input (i.e., the keyboard).

Lines 14–15

int number1; // first number to compare
int number2; // second number to compare

declare the int variables used to store the values input from the user.

Lines 17–18

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

prompt the user to enter the first integer and input the value, respectively. The input value is stored in variable number1.

Lines 20–21

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

prompt the user to enter the second integer and input the value, respectively. The input value is stored in variable number2.

Lines 23–24

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

compare the values of number1 and number2 to determine whether they're equal. An if statement always begins with keyword if, followed by a condition in parentheses. An if statement 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 24 is part of the if statement that begins at line 23. Line 24 executes only if the numbers stored in variables number1 and number2 are equal (i.e., the condition is true). The if statements in lines 26–27, 29–30, 32–33, 35–36 and 38–39 compare number1 and number2 using the operators !=, <, >, <= and >=, respectively. If the condition in one or more of the if statements is true, the corresponding body statement executes.

There's no semicolon (;) at the end of the first line of each if statement. Such a semicolon would result in a logic error at execution time. For example,

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

would actually be interpreted by Java as

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

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

Note the use of white space in Fig. 2.15. Recall that the compiler normally ignores white space. So, statements may be split over several lines and may be spaced according to your preferences without affecting a program's meaning. It's incorrect to split identifiers and strings. Ideally, statements should be kept small, but this is not always possible.

Figure 2.16 shows the operators discussed so far in decreasing order of precedence. All but the assignment operator, =, associate from left to right. The assignment operator, =, associates from right to left, so an expression like x = y = 0 is evaluated as if it had been written as x = (y = 0), which first assigns the value 0 to variable y, then assigns the result of that assignment, 0, to x.

Fig 2.16. Precedence and associativity of operators discussed.

Operators

Associativity

Type

*

/

%

left to right

multiplicative

+

left to right

additive

<

<=

>

>=

left to right

relational

==

!=

left to right

equality

=

right to left

assignment

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus