statement An else clause can be added to an if statement to make an if-else statement if ( condition ) { statement1; } else { statement2; } • If the condition is true, statement1 is executed; if the condition is false, statement2 is executed • One or the other will be executed, but not both
if Statements • The statement executed as a result of an if statement or else clause could be another if statement • These are called nested if statements • An else clause is matched to the last unmatched if (no matter what the indentation implies) • Braces can be used to specify the if statement to which an else clause belongs
Statements • Several statements are grouped together into a block statement • A block is delimited by braces: {...} • For example, in an if-else statement, the if portion, or the else portion, or both, could be block statements • There is no need to use braces if there is only one statement or one set of “if-else” within the outer “if” statement
if-else This is the same the the previous one: if (temp > 100) { System.out.println("It is hot!"); } else if (temp > 80) { System.out.println("It is warm"); } else if (temp > 50) { System.out.println("It is chilly"); } else { System.out.println("It is cold!"); }
NOT • The logical NOT operation is also called logical negation or logical complement • If some boolean condition a is true, then !a is false; if a is false, then !a is true • Logical expressions can be shown using truth tables
Operators Conditions can use logical operators to form complex expressions if (total < MAX+5 && !found) System.out.println ("Processing..."); Logical operators have precedence relationships among themselves and with other operators • The relational or arithmetic operators have higher precedence than logical AND and logical OR • logical NOT has higher precedence than logical AND. Logical AND has higher precedence than logical OR
int examGrade = 90; int assignmentGrade = 80; int quizGrade = 85; if (examGrade > 85 && assignmentGrade > 85) System.out.println(“Well done!”); else if (quizGrade < 70 || assignmentGrade < 85) System.out.println(“Houston, we have a problem”);