## The if and if/else statements

One consequent:

```   if (condition)
truestatement;```

Two alternatives:

```   if (condition)
truestatement;   else
falsestatement;```

Example 1: Only compute the average if there are grades:

```   if (numGrades != 0)

Example 2: Don't take the square root of a negative number:

```   if (value >= 0)
System.out.println("square root of " + value + " = " + Math.sqrt(value));
else
System.out.println("nonpositive number " + value + " entered"); ```

Exercise 1: What does the following do? (Trace with values.)

```   if (x > y){
temp = x;
x = y;
y = temp;
} ```
Ans: The values of x and y are exchanged. The variable temp has the original value of x.

More than one statement is included in the consequent of the if in Exercise 1, so we use curly braces ({}) to group them.

Note the difference between test for equality(==) and the assignment operator (=).

Exercise 2: Assign theMin to be the smallest of x and y.
Ans:
```   if (x <= y)
theMin = x;
else
theMin = y;```
or
`   theMin = Math.min(x, y);`

Exercise 3: Calculate wages as hoursWorked times hourlyRate with time and a half for overtime (hours over 40). This means that hours worked after the first 40 earn 1.5 times the usual rate.
Ans:
```   wages = hoursWorked*hourlyRate;
if (hoursWorked > 40)
wages += 0.5*(hoursWorked - 40)*hourlyRate; // add overtime ```

Exercise 4: Generate a random integer between 0 and 1. If the integer is 0, print out a message "You tossed heads", otherwise print out a message "You tossed tails".
Ans:
```   Random rand = new Random();
if (rand.nextInt(2) == 0)
else
System.out.println("You tossed tails"); ```

### Multiple-alternative decision

You can use as many else clauses as necessary to express multiple alteratives.

Example 3: The following code outputs a letter grade, given a grading curve.

```   if (score >= 90)
else if (score >= 80)
else if (score >= 70)
else if(score >= 60)
else
System.out.println("Score is " + score); ```

### Nested selection statements in the if clause

Nested selection occurs when either the true clause or the false clause are themselves an if statement. When the nesting occurs in the if, the code can be very confusing. You should try to avoid nested if-else statements if there are suitable alternatives. (There almost always are!)

Exercise 5: What happens in the following when x has value 5 and y has value 2?

```   if (x >= 0)
if (y >= x)
System.out.println(" y >= x >= 0 ");
else
System.out.println("expression not satisfied for non-negative x" ); ```
Ans: The result is probably not what you think. The Java rule for matching else with if is that Java matches each else with the closest preceding if that is not matched with a closer else. (It doesn't matter how YOU indent.)

An equivalent version using {} for clarity only:

```    if (x >= 0){
if (y >= x)
System.out.println(" y >= x >= 0 ");
else
System.out.println("expression not satisfied for non-negative x");
}```

A better implementation eliminating the nested if-else uses the boolean operators described next:

```    if (x >= 0 && y >= x)
System.out.println(" y >= x >= 0 ");
else if (x >= 0 && y < x)
System.out.println("expression not satisfied for non-negative x");
```

What was probably intended can be implemented with:

```   if (x >= 0) {
if (y >= x)
System.out.println(" y >= x >= 0 ");
}
else
System.out.println("expression not satisfied for non-negative x" ); ```
or better:
```    if (x >= 0 && y >= x)
System.out.println(" y >= x >= 0 ");
else
System.out.println("expression not satisfied for non-negative x");
```
Exercise 6: Why is the following incorrect?
```   if (y >= x >= 0)
System.out.println(" y >= x >= 0 ");```
Ans: The >= can only have two operands. Evaluation occurs left to right. The evaluation of y >= x results in a boolean. At this point you are comparing a boolean value with the int 0. The two operands are not of compatible types.

Try to avoid the nesting of selection in the if clause, it is almost always hard to figure out. Instead, reorganize your code or use boolean operators to combine conditions.