Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 9 if-else 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
Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 11 Nested 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
Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 13 Block 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
Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 16 if-else 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!"); }
Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 17 Logical 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
Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 18 Logical AND and Logical OR • Since && and || each have two operands, there are four possible combinations of conditions a and b
Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 19 Logical 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
Javier Gonzalez-Sanchez | CSE110 | Summer 2020 | 20 Example 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”);
CSE110 - Principles of Programming Javier Gonzalez-Sanchez [email protected] Summer 2020 Disclaimer. These slides can only be used as study material for the class CSE110 at ASU. They cannot be distributed or used for another purpose.