Module 4
Chapter 4: Introduction to Program Design and Data Structures
Chapter Scope
Flow of Control: Understanding how program statements are executed.
Boolean Expressions: Conditions that evaluate to true or false.
Conditional Statements: Utilizing if and switch statements for decision-making.
Comparing Data: Understanding equality and relational operators.
Loops: Using while, do, and for loops for repetition.
Iterators: Processing collections of items one at a time.
Flow of Control
Statement execution is linear unless directed otherwise.
Some statements allow decisions to execute or skip statements based on conditions.
Flow of control refers to the order in which statements are executed, governed by boolean expressions.
Conditional Statements
Conditional statements (or selection statements) enable decision-making in programs. The primary types in Java are:
if statement
if-else statement
switch statement
The if Statement
Syntax:
if (condition) statement;
The
condition
must be a boolean expression; if true, the statement executes.If false, the statement is skipped.
Equality and Relational Operators
Conditions typically use:
Equality Operators (e.g.,
==
,!=
)Relational Operators (e.g.,
<
,>
,<=
,>=
)
Example Conditions
if (total == sum) System.out.println("total equals sum");
if (count > 50) System.out.println("count is more than 50");
if (letter != 'x') System.out.println("letter is not x");
Logical Operators
Logical NOT (
!
): Negates the boolean value.Example: If
a
is true,!a
is false, and vice versa.
Logical AND (
&&
): True if both operands are true.Logical OR (
||
): True if at least one operand is true.
Short-Circuited Operators
Processing of logical AND/OR may not evaluate the second operand if the first operand determines the result.
Example:
if (count != 0 && total/count > MAX)
; ifcount
is 0, the second condition is not evaluated.
The if-else Statement
Structure:
if (condition) statement1; else statement2;
Executes
statement1
if true; otherwise,statement2
executes.
Block Statements
A group of statements can be enclosed in braces
{}
, treated as a single statement in control structures.
The Conditional Operator
Syntax:
condition ? expression1 : expression2;
Equivalent to an if-else statement that evaluates to a value based on a condition.
Nested if Statements
Statements can be nested, allowing for more complex decision-making.
Comparing Data
Floating Point Comparisons: Use caution with
==
due to representation issues; consider using a tolerance.Character Comparisons: Based on Unicode values allowing the use of relational operators.
String Comparisons: Utilize
.equals()
for equality and.compareTo()
for order comparisons.
The switch Statement
Provides a way to select execution based on an expression's value.
Syntax:
switch (expression) {
case value1:
statement-list1;
break;
case value2:
statement-list2;
break;
}
Default case: Handles situations where no match is found.
Loops
Types of Loops:
while loop: Executes as long as the condition is true.
do while loop: Executes at least once before checking the condition.
for loop: Iterates a specific number of times, ideal for counting.
The while Loop
Syntax:
while (condition) { statement; }
Executes the statement while condition remains true.
The for Loop
Syntax:
for (initialization; condition; increment) { statement; }
Combines initialization, condition checking, and incrementing in one line.
Iterators
An iterator processes collections item by item, using methods like hasNext()
and next()
to control the iteration.
Example: Scanner class as an iterator to read inputs.
Conclusion
Understanding conditionals and loops is fundamental to controlling the flow of a Java program, leveraging boolean expressions for decision-making and repetition.
The switch Statement
The switch statement is a control structure that allows execution to be selected based on the value of an expression. It provides a convenient way to handle multiple conditions without the need for multiple if-else statements. The syntax and working of the switch statement are outlined below:
Syntax:
switch (expression) {
case value1:
statement-list1;
break;
case value2:
statement-list2;
break;
// more cases...
default:
default-statement-list;
}
Components:
Expression: The switch statement evaluates this expression. It must yield a value that can be compared against the values defined in the case blocks.
Case Labels: Each
case
is followed by a value that is compared to the expression. If they match, the associated statements are executed.Break Statement: After executing the statements in a case, it is common to use a
break
statement to exit the switch block. If the break is omitted, execution will continue into the next case (fall-through behavior).Default Case: This is optional and catches any values that do not match any of the specified cases. It’s similar to the last else statement in an if-else structure.
Example:
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
System.out.println(dayName); // Outputs: Wednesday
Characteristics:
Variable Types: The expression must be of a type that can be compared using equality (e.g. int, char, String). Note that switch statements cannot directly check for range.
Fall-Through: If a case does not have a break statement, execution continues to the next case, which can be useful in certain scenarios but can also lead to unexpected behavior if not handled properly.
Performance: In some cases, switch statements can be more efficient than lengthy if-else chains, especially when there are many conditions to evaluate.
Conclusion:
Switch statements are useful for simplifying complex conditional logic, making code clarity and management easier when handling multiple discrete values.