expressions A condition uses relational operators, which all return boolean results: == equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator (==) and the assignment operator (=)
of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after the other in sequence (top down order). public static void main (String [] args) { System.out.println(“one”); System.out.println(“two”); System.out.println(“three”); } The order of statement execution is called the flow of control
of Control Some programming statements modify that order (flow of control), allowing us to: • decide whether to execute a statement, or • perform a statement over and over, repetitively These decisions are based on a boolean expression (also called a condition) that evaluates to true or false.
Statements • A conditional statement lets us choose which statement will be executed next • Java's conditional statements are o the if statement o the if-else statement o the switch statement o the operator ?
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
if-else You can also have multiple conditions to be verified: 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!"); }
if-else The code from the previous page is equivalent to: 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!"); } } }