Chapter 3 Control Statements

 

The boolean Type and Operators

Often in a program you need to compare two values, such as whether i is greater than j. Java provides six comparison operators (also known as relational operators) that can be used to compare two values. The result of the comparison is a Boolean value: true or false.

boolean b = (1 > 2);

 

&&: conditional AND operator

&: unconditional AND operator

||: conditional OR operator

|: unconditional OR operator

 

exp1  && exp2

(1 < x) && (x < 100)

 

(1 < x) & (x < 100)

The & and | Operators

If x is 1, what is x after this expression?

(x > 1) & (x++ < 10)

 

If x is 1, what is x after this expression?

(1 > x) && ( 1 > x++)

 

How about (1 == x) | (10 > x++)?

(1 == x) || (10 > x++)?

 

 

Selection Statements

Simple if Statements

if (booleanExpression) {

  statement(s);

}

Note

Caution

Adding a semicolon at the end of an if clause is a common mistake.

if (radius >= 0);

 

 

 

 

 

{

  area = radius*radius*PI;

  System.out.println(

    "The area for the circle of radius " +

    radius + " is " + area);

}

This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error.

This error often occurs when you use the next-line block style.

 

 

The if...else Statement

if (booleanExpression) {

  statement(s)-for-the-true-case;

}

else {

  statement(s)-for-the-false-case;

}

if...else Example

if (radius >= 0) {  

  area = radius * radius * 3.14159;

 

  System.out.println("The area for the “ 

    + “circle of radius " + radius +

    " is " + area);

}

else {

  System.out.println("Negative input");

}

 

Note

The else clause matches the most recent if clause in the same block.

Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces:

  int i = 1;

  int j = 2;

  int k = 3;

  if (i > j) {

    if (i > k)

      System.out.println("A");

  }

  else

    System.out.println("B");

This statement prints B.

 

 

 

Example: Computing Taxes

The US federal personal income tax is calculated based on the 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.1.

Example: Computing Taxes, cont.

if (status == 0) {

  // Compute tax for single filers

}

else if (status == 1) {

  // Compute tax for married file jointly

}

else if (status == 2) {

  // Compute tax for married file separately

}

else if (status == 3) {

  // Compute tax for head of household

}

else {

  // Display wrong status

}

 

 

Example: An Improved Math Learning Tool

This example creates a program to teach a first grade child how to learn subtractions. 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 the figure. 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.

 

 

switch Statements

switch (status) {

  case 0:  compute taxes for single filers;

           break;

  case 1:  compute taxes for married file jointly;

           break;

  case 2:  compute taxes for married file separately;

           break;

  case 3:  compute taxes for head of household;

           break;

  default: System.out.println("Errors: invalid status");

           System.exit(0);

}

 

 

switch Statement Rules

The keyword break is optional, but it should be used at the end of each case in order to terminate the remainder of the switch statement. If the break statement is not present, the next case statement will be executed.

 

 

if (x > 0)

  y = 1

else

  y = -1;

 

is equivalent to

 

y = (x > 0) ? 1 : -1;

(booleanExpression) ? expression1 : expression2

 

Ternary operator

Binary operator

Unary operator

 

 

Conditional Operator

if (num % 2 == 0)

  System.out.println(num + “is even”);

else

  System.out.println(num + “is odd”);

 

 

System.out.println(

  (num % 2 == 0)? num + “is even” :

  num + “is odd”);

.

(booleanExp) ? exp1 : exp2

 

 

Formatting Output

 

Creating Formatted Strings

System.out.printf(format, item1, item2, ..., itemk)

 

 

Operator Precedence

F     var++, var--

F     +, - (Unary plus and minus), ++var,--var

F     (type) Casting

F     ! (Not)

F     *, /, % (Multiplication, division, and remainder)

F     +, - (Binary addition and subtraction)

F     <, <=, >, >= (Comparison)

F     ==, !=; (Equality)

F     & (Unconditional AND)

F     ^ (Exclusive OR)

F     | (Unconditional OR)

F     && (Conditional AND) Short-circuit AND

F     || (Conditional OR) Short-circuit OR

F     =, +=, -=, *=, /=, %= (Assignment operator)

 

 

Operator Precedence and Associativity

The expression in the parentheses is evaluated first. (Parentheses can be nested, in which case the expression in the inner parentheses is executed first.) When evaluating an expression without parentheses, the operators are applied according to the precedence rule and the associativity rule.

 

If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left-associative. 

Operator Associativity

    When two operators with the same precedence are evaluated, the associativity of the operators determines the order of evaluation. All binary operators except assignment operators are left-associative.

    a – b + c – d is equivalent to  ((a – b) + c) – d

    Assignment operators are right-associative. Therefore, the expression

    a = b += c = 5 is equivalent to a = (b += (c = 5))

 

Example

Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows:

Operand Evaluation Order

The precedence and associativity rules specify the order of the operators, but do not specify the order in which the operands of a binary operator are evaluated. Operands are evaluated from left to right in Java.

The left-hand operand of a binary operator is evaluated before any part of the right-hand operand is evaluated.

 

If no operands have side effects that change the value of a variable, the order of operand evaluation is irrelevant. Interesting cases arise when operands do have a side effect. For example, x becomes 1 in the following code, because a is evaluated to 0 before ++a is evaluated to 1. 

int a = 0;

int x = a + (++a);

But x becomes 2 in the following code, because ++a is evaluated to 1, then a is evaluated to 1.

int a = 0;

int x = ++a + a;

Rules of Evaluating an Expression

Rule 1: Evaluate whatever subexpressions you can possibly evaluate from left to right.

   

Rule 2: The operators are applied according to their precedence.

      

Rule 3: The associativity rule applies for two operators next to each other with the same precedence.

: