Flow of Control: Branching (Savitch, Chapter 3)
TOPICS
- Conditional Execution
- if, else, and else if
- boolean data
- switch statements
1 CS 160, Summer Semester 2016
if Statement
- Programs often contain statements that may or may
not be executed depending on conditions.
- An if statement checks whether a condition is true
before deciding whether to execute some code.
- Conditions typically involve comparison of variables or
quantities for equality or inequality.
- Example:
if (age >= 18)
System.out.println(“You are eligible to vote.”);
CS 160, Summer Semester 2016 2
Expression in parenthesis must evaluate to either true
- r false
The if Statement
- The if statement has the following syntax
if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped.
3 CS 160, Summer Semester 2016
Numeric Relational Operators
Math Java description < < Less than > > Greater than <= Less than or equal to >= Greater than or equal to = == Equal to != Not equal to
4 CS 160, Summer Semester 2016