Title: Introduction to Programming with Java, for Beginners
1Introduction to Programmingwith Java, for
Beginners
- Conditionals (if statements)
2Conditionals (if statements)
- An if statement is a flow control control
statement - It is also called a conditional, or a branch
- Well 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, well look at some examples then well
look at - the syntax (grammar rule)
3Examples of if statements
// assume x and max are ints if (x gt 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.)
4if statement
if (condition) statement
if (condition) statement(s)
- If the condition is true, then the statement(s)
will be executed. - Otherwise, they wont.
5Example how to swap
int num1 40 int num2 20 // Let num1 store the smaller if (num1 gt num2) int temp 0 temp num1 num1 num2 num2 temp Heres 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.
6if-else statement
Example Syntax Explanation
int x 5 int y 10 int min -9999 if (x lt 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.
7Cascading if-else
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.)
8Nested if-statments
An if within an if Truth 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?
A B C
condition1 T
condition2
9The infamous dangling else
Code Notes
if (condition 1) if (condition 2) statementA else statementB When is statementB 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
if (condition 1) if (condition 2) statementA else statementB