Selection
- Selection statements are used to control the flow of a program by executing specific blocks of code based on certain conditions.
- They enable programs to make decisions, allowing for dynamic and flexible behaviour.
- Imagine an ATM.
- It needs to check if your card is valid and if your PIN is correct before allowing access to your account.
Types of Selection Statements
Simple if statements: Execute a block of code if a condition is true.
Exampleif (age < 18){
System.out.println("You are not eligible to vote.");
}- The condition age $< 18$ is evaluated.
- If true, the message "You are not eligible to vote." is printed.
- Always ensure that the condition inside the if statement is a boolean expression that evaluates to true or false.
- When programming, avoid using the assignment operator (=) instead of the equality operator (==) in conditions.
if...else statements: Provide an alternative block of code if the condition is false.
Exampleif (age < 18){
System.out.println("You are not eligible to vote.");
} else {
System.out.println("You are eligible to vote.");
}- The condition age $< 18$ is evaluated.
- If true, the message "You are not eligible to vote." is printed.
- If false, the else block is executed, printing "You are eligible to vote."
- The else block is optional.
- If omitted, the program simply skips the if block if the condition is false.
Compound if...else statements: Handle multiple conditions using else if clauses.
Exampleif (points > 90){
grade = "A";
} else if (points > 60){ \\ if points in (60, 90]
grade = "B";
} else{
grade = "C";
}- The program checks each condition in order.
- Once a true condition is found, the corresponding block is executed, and the rest are skipped.
The else block at the end is optional but useful for handling cases where none of the previous conditions are met.