Introduction to Programming with Java for Beginners Conditionals

Introduction to Programming with Java, for Beginners Conditionals (if statements)

Conditionals (“if” statements) § An if statement is a “flow control” control statement § It is also called a conditional, or a branch § We’ll see several “flavors” § An if all by itself § An if with an else part § An if with an else if part § A cascading series of the above § First, we’ll look at some examples; then we’ll look at the syntax (grammar rule) 1

Examples of “if” statements // assume x and max are ints if (x >= max) max = x; boolean result; // assume code here sets result to be true or false if (result == true) // if (result) System. out. println(“result is true. ”); else System. out. println(“result is false. ”); 2

“if” statement if (condition){ statement(s) } If the condition is true, then the statement(s) will be executed. Otherwise, they won’t. 3

Example: how to swap int num 1 = 40; int num 2 = 20; // Let num 1 store the smaller # if (num 1 > num 2){ int temp = 0; temp = num 1; num 1 = num 2; num 2 = temp; } Here’s how to “swap” the values of two variables by using a temporary variable. This is a common pattern used for swapping all kinds of data. 4

“if-else” statement Example int x = 5; int y = 10; int min = -9999; if (x <= y){ min = x; } else { min = y; } Syntax & Explanation if (condition){ statement(s) } else { statements(s) } If the condition is true, then the statement(s) in the “if block” are executed. Otherwise, if there is an “else” part, the statement(s) in it are executed. 5

Cascading “if-else” Example char user. Choice; // Ask user for input and store it in user. Choice if (user. Choice == ‘q’) System. out. println(“quitting. ”); else if (user. Choice == ‘a’) System. out. println(“adding. ”); else if (user. Choice == ‘s’) System. out. println(“saving. ”); else System. out. println(“unrecognized choice. ”); 6

Nested if-statments An if within an if if (condition 1){ if (condition 2){ statement(s) A } else{ statement(s) B } } else { statements(s) C } Truth Table What values must the conditions have in order for block A to run? B? C? A condition 1 B C T condition 2 7

The infamous “dangling else” Code if (condition 1) if (condition 2) statement. A; else statement. B; Notes When is statement. B executed? In other words, which if is the else paired with? An else is paired with the last else-less if, regardless of spacing, unless { } dictate otherwise. A fix: n if (condition 1){ if (condition 2) statement. A; } else statement. B; 8
- Slides: 9