Download presentation
Presentation is loading. Please wait.
1
Introduction to Programming with Java, for Beginners Conditionals (if statements)
2
1 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)
3
2 // assume x and max are ints if (x >= max) max = x; Examples of “if” statements 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.”);
4
3 “if” statement If the condition is true, then the statement(s) will be executed. Otherwise, they won’t. if (condition) statement if (condition){ statement(s) }
5
4 int num1 = 40; int num2 = 20; // Let num1 store the smaller # if (num1 > num2){ int temp = 0; temp = num1; num1 = num2; num2 = 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. Example: how to swap
6
5 ExampleSyntax & Explanation int x = 5; int y = 10; int min = -9999; if (x <= y){ min = x; } else { min = y; } 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. “if-else” statement
7
6 Example char userChoice; // Ask user for input and store it in userChoice if (userChoice == ‘q’) System.out.println(“quitting.”); else if (userChoice == ‘a’) System.out.println(“adding.”); else if (userChoice == ‘s’) System.out.println(“saving.”); else System.out.println(“unrecognized choice.”); Cascading “if-else”
8
7 An if within an ifTruth Table if (condition1){ if (condition2){ statement(s) A } else{ statement(s) B } else { statements(s) C } What values must the conditions have in order for block A to run? B? C? Nested if-statments ABC condition1 T condition2
9
8 CodeNotes if (condition 1) if (condition 2) statementA; else statementB; When is statementB executed? In other words, which if is the else paired with? The infamous “dangling else” An else is paired with the last else-less if, regardless of spacing, unless { } dictate otherwise. A fix: if (condition 1){ if (condition 2) statementA; } else statementB;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.