DECISION STRUCTURES: USING IF STATEMENTS IN JAVA S o far all the programs we have created run straight through from start to finish, without making any decisions along the way. Many times, however, you may need to execute a different set of code based on criteria input by the user. Just as you might say to yourself, If she doesn t call me, I am not going to speak to her again, a computer program uses decision structures to decide what actions to take depending on certain conditions. The decision structure Java programmers use to perform this type of conditional logic are called if statements. All if statements use boolean expressions to determine whether to execute or skip a statement (or a block of statements). A boolean experession is a Java expression that, when evaluated, returns a boolean value that is, either true or false. Boolean expressions often compare the value of a variable with the value of some other variable, a literal, or perhaps a simple arithmetic expression through the user of something called a relational operator. RELATIONAL OPERATORS Java evaluates a boolean expression by first evaluating the expression on the left, then evaluating the expression on the right, and finally applying the relational operator to determine if the entire expression evaluates to true or false. The equal sign (==), for example, is a relational operator that compares the value of the expression to the left, with the value of the expression to the right. It always returns a TRUE or FALSE value. if (score == 0) The following are six (6) Java relational operators that are used to evaluate boolean expressions: OPERATOR NAME DESCRIPTION EXAMPLE < Less than Returns true if the expression on the left evaluates to a value that is less than the value of the expression on the right. if (score < 100) <= Less than or equal Returns true if the expression on the left evaluates to a value that is less than or equal to the value of the expression on the right. if (score <= 100) == Equal Returns true if the expression on the left evaluates to a value that is equal to the value of the expression on the right. if (score == 100) MAKING DECISIONS: Using If Statements in Java Page 1 of 8
!= Not equal Returns true if the expression on the left does not equal the value of the expression on the right. if (score!= 100) >= Greater than or equal Returns true if the expression on the left evaluates to a value that is greater than or equal to the value of the expression on the right. if (score >= 100) > Greater than Returns true if the expression on the left evaluates to a value that is greater than the value of the expression on the right. if (score > 100) Note that the relational operator that tests for equality is two equal signs in a row (==). A single equal sign is the assignment operator. So if you try to use a single equal sign in a boolean expression you will get a compile-time error. THE if STATEMENT In its most basic form, an if statement lets you execute a single statement or a block of statements only if a boolean expression returns true. The following is the basic form of the if statement: if (boolean-expression) statement Note that the boolean expression must be enclosed in parentheses. Also, if you use only a single statement, it must end with a semicolon. But the statement can also be a statement enclosed by braces. In that case, each statement within the block needs a semicolon, but the block itself doesn t. Here s an example of a typical if statement: double hourlyrate = 10; In this example, a variable named hourlyrate is initialized to 8.00, and then set to 10.00 if hoursworked is greater than 40. So what will hourlyrate be equal to if hoursworked is not greater than 40. If you answered 8.00, you re correct! Indenting the statement under the if statement is customary to make the structure of your code more obvious. It isn t necessary, but always a good idea. Here s an example that uses a block rather than a single statement: double MAKING DECISIONS: Using If Statements in Java Page 2 of 8
hourlyrate = 10; totalpay = hoursworked * hourlyrate; In the above example, the two statements within the braces are executed if hoursworked is greater than 40. Otherwise, neither statement is executed. Keep in mind that indentation by itself doesn t create a block. For example, consider this example: double hourlyrate = 10; totalpay = hoursworked * hourlyrate; In the above example, I didn t use the braces to mark a block, but indented the last statement as if it were part of the if statement. This will result in the last statement being executed whether or not the expression in the if statement returns true. It might be a good idea to always code if statements using statement blocks regardless of the number of statements that conditionally execute, as the following example illustrates: hourlyrate = 10; The reason why this would not be a bad idea is because it makes the structure of your code a little more obvious by adding extra white space around the statement. Also, if you later decide you need to add a few statements to the block, the braces are already there. THE if- STATEMENT Unlike an if statement which executes an instruction(s) if the conditional expression returns true, an if statement includes an optional clause that is executed if the conditional expression returns false. The basic format of an if- statement is: if (boolean-expression) statement statement Here s an example that uses an if- statement to determine one s hourly rate: double hourlyrate; MAKING DECISIONS: Using If Statements in Java Page 3 of 8
In this example, the hourlyrate is set to 10.00 if the hoursworked is greater than 40. If the hoursworked is not greater than 40, then the hourlyrate is set to 8.00. You can, of course, write the above statement using blocks as follows: double hourlyrate; NESTED if STATEMENTS The statement that goes in the if or part of an if- statement can be any kind of Java statement, including another if or -if statement. This is called NESTING, and an if or if- statement that includes another if or -if statement is called a NESTED IF STATEMENT. The general form of a nested if statement is as follows: if (expression1) if (expression2) statement1 statement2 if (expression3) statement3 statement4 In this example, expression1 is first evaluated. If it returns true, expression2 is evaluated. If that expression is true, statement1 is executed; otherwise statement2 is executed. But if expression1 is false, then expression3 is evaluated. If expression3 is true, statement3 is executed; otherwise statement4 is executed. Suppose I have two classes of employees: part-timers and full-timers and they get a different hourly rate based on the number of hours they work. I could implement a pay structure with a nested if statement as follows: MAKING DECISIONS: Using If Statements in Java Page 4 of 8
if (parttime == true) hourlyrate = 12.00; OR if (parttime == true) hourlyrate = 12.00; This example assumes that if the parttime variable isn t true, then the employee must be a full-time employee. In the above example, what would be my hourly rate if I was a full-time employee who worked a total of 40 hours? If you said 12.00, you are correct! THE if- if STATEMENT A common pattern for nested if statements is to have a series of if- if statements: The general format of an if- if statement is as follows: MAKING DECISIONS: Using If Statements in Java Page 5 of 8
if (expression1) statement1 if (expression2) statement2 if (expression3) statement3 For example, suppose I want to assign four different hourly rates based on the amount of hours worked. I can easily implement a series of if- if statements to assign different rates by doing the following: if (hoursworked > 30) hourlyrate = 12.00; if (hoursworked > 20) It is important to keep in mind that your boolean expression must be properly ordered because statements are executed for the first true condition only, and skips all the other conditions. For example, if I had changed the sequence of my statements to look like this, what would the hourly rate be for an employee who works 60 hours? if (hoursworked > 0) if (hoursworked > 20) if (hoursworked > 30) hourlyrate = 12.00; If you said 8.00, you re correct! These if statements sets the hourlyrate to 8.00 because the boolean expression in the first statement always returns true (assuming the hoursworked variable isn t zero or negative), thus resulting in the other if statements never being evaluated. THE switch STATEMENT The switch statement is sometimes useful when you need to select one of several alternatives based on the value of an integer or character type variable. The following is the basic form of a switch statement: switch (expression) case constant1: statements; break; MAKING DECISIONS: Using If Statements in Java Page 6 of 8
case constant2: statements; break; case constant3: statements; break; default: statements; break; You can code as many case groups as you want or need. Each begins with the word case followed by a constant (usually a simple numeric literal) and a colon. Then you code one or more statements that you want executed if the value of the switch expression equals the constant. The last line of each case group is a break statement, which causes the entire switch statement to end. The default group, which is optional, is like a catch-all case group. Its statements are executed only if none of the previous case constants match the switch expression (very similar to an statement). BOOLEAN OPERATORS Sometimes we may want our program to perform an action if more than one condition (logical AND) or one of multiple conditions is true (logical OR). For example, I may want to set an employee s hourly rate to 14.00 if he/she is a full-time employee and works more than 40 hours a week. In this case we need to use a BOOLEAN OPERATOR. Boolean operators let you combine two or more conditions in the same expression. if (fulltime == true && hoursworked > 40) The following are Boolean operators that can be used to form more complex Boolean expressions: OPERATOR LOGIC BOOLEAN EXAMPLE && Both conditions must be true Either condition must be true! Result of the condition is reversed AND if (fulltime == true && hoursworked > 40) OR if (fulltime == true hoursworked > 40) NOT if!(hoursworked > 40) MAKING DECISIONS: Using If Statements in Java Page 7 of 8
^ One and only one of the conditions is true XOR if (fulltime == true ^ hoursworked > 40) ILLUSTRATING BOOLEAN EXPRESSIONS WITH TRUTH TABLES How a compound Boolean expression evaluates with && and operators can be illustrated with TRUTH TABLES. Truth tables show the possible outcomes of compound Boolean expressions. AND (&&) A B RESULT True True True True False False False True False False False False OR ( ) A B RESULT True True True True False True False True True False False False XOR (^) A B RESULT True True False True False True False True True False False False A True False NOT (!) RESULT False True MAKING DECISIONS: Using If Statements in Java Page 8 of 8