| The If Statement The order in which a program's statements are executed is referred to as the program's flow.
A simple flow is simply one statement after another:
public class Demo
{
public static void main(String [] args)
{
System.out.println("One"); // 1
System.out.println("Two") // 2
System.out.println("Three"); // 3
System.out.println("Four"); // 4
}
}
The program shown above has a simple and very predictable flow -- statement one is executed, then statement two, then statement three, and finally statement four. Each statement is executed exactly once.
It is possible to choose whether or not to execute a statement, based on some condition, using an if statement. The general form of the if statement is:
if (boolean_expression)
statement
For example, if a program has an int variable named salary, then the following if statement could be written:
if (salary > 1000)
System.out.println("Wow!");
If the value in salary is greater than 1000, then "Wow!" is printed. If salary is 1000 or less, the "Wow!" statement is skipped and nothing is printed. The if statement does not affect the statements before or after the if statement. In the example below, the "Before" and "After" statements are performed regardless of what happens with the if statement:
System.out.println("Before");
if (salary > 1000)
System.out.println("Wow!");
System.out.println("After");
The two possible outputs for this Java code are either
Before
Wow!
After
for any value of salary greater than 1000, or
Before
After
if salary contains a value of 1000 or less.
The if statement chooses whether or not to execute a statement. The if-else statement chooses between two different statements.
The If-Else Statement
The general form of the if-else statement is
if (boolean_expression)
statement1
else
statement2
If the boolean expression is true, then statement1 is performed (and statement2 is skipped), otherwise statement2 is performed (and statement1 is skipped).
For example, if a program had an int variable hours, then the following code could be written:
if (hours > 40)
System.out.println("Overtime pay!");
else
System.out.println("Regular hours");
Only one of the two outputs, "Overtime pay!" or "Regular hours" will be generated by the above code.
Compound Statements
The statements affected by a if or if-else statement can either be a simple statement:
if (speed > 70)
System.out.println("Pretty fast!");
or a compound statement. A compound statement is a single statement that is made up of several pieces, such as when you collect several seperate statements together using curly braces: {}. For example:
if (speed > 70)
{
System.out.println("Pretty fast!");
System.out.println("Keep your eyes on the road.");
}
else
{
System.out.println("You still have to pay attention.");
System.out.println("Even at slower speeds.");
}
In the example above, the two statements
System.out.println("Pretty fast!");
System.out.println("Keep your eyes on the road.")
are grouped together with {}s to make a single compound statement
{
System.out.println("Pretty fast!");
System.out.println("Keep your eyes on the road.")
}
The first compound statement is executed if the condition of the if statement is true. The other compound statement is executed if the condition is false. Therefore, the output will either be
Pretty fast!
Keep your eyes on the road.
or
You still have to pay attention.
Even at slower speeds.
Relational and Logical Operators
The boolean expressions in if and if-else statements often involve the use of relational and logical operators. You are already familiar with arithmetic operators, such as *, /, %, + and -. Expressions of involving these operators yield numeric results (e.g., 3 * 10 yields 33). Relational and logical operators are used to form expressions that yield one of the two boolean values of either true or false (in Java the boolean values of true and false must be written in all lowercase letters).
Relational Operators
Here are the six relational operators:
| Operator |
Description |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
== |
Equal |
!= |
Not equal |
Here are some examples of some expressions involving relational operators, and their resulting boolean values:
| Expression |
Value |
15 > 3 |
true |
100 != 62 |
true |
3 >= 20 |
false |
5 > 5 |
false |
11 >= 11 |
true |
For these examples, assume that the int variable hours has been declared and currently has the value of 15:
| Expression |
Value |
hours > 40 |
false |
hours <= 30 |
true |
hours > 15 |
false |
Logical Operators
The three logical operators: && , || and ! represent the actions of AND, OR and NOT, respectively. The and || operators are used to combine boolean expressions, the ! operator is used to reverse a boolean value.
The && operator takes two boolean operands -- if both operands are true, then the entire expression is true -- otherwise it is false:
| Expression |
Value |
| true && true |
true |
| true && false |
false |
| false && true |
false |
| false && false |
false |
The || operator takes two boolean operands -- if either or both of the operands is true, then the entire expression is true -- the expression is only false if both operands are false:
| Expression |
Value |
| true || true |
true |
| true || false |
true |
| false || true |
true |
| false || false |
false |
The ! operator takes a single boolean operand and reverses its value:
| Expression |
Value |
| !true |
false |
| !false |
true |
The relational and logical operators are often used together to express a complex condition for an if or if-else statement. For example, a payroll program might only give a bonus to workers who have been with the company for two or more years, and have worked at least eighty hours in the last month:
if (years >= 2 && hours > 80)
paycheck += bonus;
Since the && operator is used here, the worker only gets the bonus if both conditions are true (years >= 2 and hours > 80). If either condition is false then the entire expression is false, and the statement to add in a bonus amount is skipped.
The next example simulates a game in which a player rolls two dice (six-sided dice). The sum of the two dice yields a value from 2 to 12. If the player rolls either a 7 or an 11 on the first roll of the dice then they win the game:
if (sum == 7 || sum == 11)
System.out.println("You win!");
Notice the difference between the || and the && operators. For the years >= 2 && hours > 80 expression to be true both operands need to be true (years >= 2 and hours > 80 for the paycheck to get a bonus). But with the sum == 7 || sum == 11 expression just one of the operands needs to be true (if sum is sum == 7 or sum == 11 then you win).
Now that we've learned some new operators, we can update the precedence table. The table includes an indication of the type of operator (arithmetic, logical, relational) and its associativity. Operators toward the top of the table have a higher precedence that operators that are found lower in the table.
Operator Precedence Table
| Type |
Operator |
Associativity |
| Logical |
! |
Left-to-right |
| Arithmetic |
* / % |
Left-to-right |
| Arithmetic |
+ - |
Left-to-right |
| Relational |
> >= < <= |
Left-to-right |
| Relational |
== != |
Left-to-right |
| Assignment |
= |
Right-to-left |
| Logical |
&& |
Left-to-right |
| Logical |
|| |
Left-to-right |
More complicated expressions, involving several types of operators, can be solved with the use of the above precedence table. The expression below checks to see if adding three hours to someone's work-week will put them over the twenty hour limit required to maintain their part-time status.
hours + 3 > 20
Assume that hour is 18. Then we have:
18 + 3 > 20
The expression has two operators: + and >. The precedence table shows that the + operator has a higher precedence than >, therefore the addition is performed first to get:
21 > 20
Then the > operator is evaluated to yield
true
Examples
At this point you should be able to give the value of each of the following expressions:
!true
!!!false
5 > 3
!(10 < 2)
true && true
false || false
false || true
true && false
true && true && true && false && true
true || false || true || false
true || false && true
true && false || true
false && true || false
false || true && false
!true && false
!(true && false)
5 > 3 && 4 < 6
1000 != 2 && 50 > 4
16 > 3 || 2 > 35
After you have solved these on your own, compare to these answers. Here are some more examples, involving the variables food and drinks, where food is set to 15 and drinks is set to 9. Calculate the value of each of these expressions:
food < 30 && drinks < 10
food + drinks <= 20
drinks > food
(food + drinks) * 0.10 > 5
food > 20 || drinks > 5
Here are the answers to the expressions shown above..
|