Computer Programming I Instructor: Greg ShawCOP 2210The if Statement I. PurposeJava's if statement is used make decisions. That is, to allowa different sequence of statements to be executed depending onwhether a condition is true or false.II. The Single-Alternative if Statement (“yes/no”decisions)Syntax:if (boolean expression){statement(s) } where, boolean expression = something that evaluates to true orfalse. One kind of booleanexpression is the relationalexpression, which compares twoquantities for one of these 6relationships: <, <=, >, >=, ==,and != statement(s) = any number of Java statements. Naturally,each statement must end with a semi-colon.(Note: the parentheses are required, and that there is nosemi-colon after the closing parenthesis.)Execution:1. The boolean expression is evaluated.2. If it is true, then the statement(s) are executed.Otherwise (i.e., if it is false), the statement(s) areskipped.For this reason, the single-alternative if statement is knownas a “yes/no” decision. Example: see program PayMaster1.javaIII. The Two-Alternative if Statement (“either/or”decisions)Syntax:if (boolean expression){statement(s) }else{other statement(s)}Execution:1. The boolean expression is evaluated.2. If it is true, then the statement(s) in the “if” branchare executed, and the other statement(s) (i.e., the“else” branch) are skipped.Otherwise (i.e., if it is false), then the statement(s)in the “if” branch are skipped, and the otherstatement(s) (i.e. the “else” branch) are executed.For this reason, the two-alternative if statement is known asan “either/or” decision. The keyword else is computer-talkfor “otherwise.”Example: see program PayMaster2.javaIV. “Nested” if Statements - A “nested if” statement is an if statement inside another ifstatement - When the nested if is in the if branch, more complexconditions are produced- When the nested if is in the else branch, a multiple-alternative (i.e., “one of several”) if statement is produced- More complex conditions can also be produced using theboolean operators (see the document, “Boolean Operators andExpressions”)- For examples of nested ifs, see the document “Nested
View Full Document