CHAPTER 05
1. Control Flow in Java
• Sequential Programming: Code runs from top to bottom, one line at a time.
• Conditional Programming: Code execution depends on specific conditions (e.g., if a user
is below 18 years old).
2. IF Statements
• The if statement runs a block of code if a condition is true.
• Example:
if (user < 18) {
[Link]("You are a minor.");
3. Comparison Operators
• <: Less than
• >: Greater than
• <=: Less than or equal
• >=: Greater than or equal
• ==: Equal to
• These operators are used to compare values.
4. IF…ELSE Statements
• Use an if…else statement when there are two possible outcomes: one when the
condition is true, and the other when it's false.
• Example:
if (user < 18) {
[Link]("You are a minor.");
} else {
[Link]("You are an adult.");
IF…ELSE IF Statements
• This allows you to handle more than two choices by adding multiple else if conditions.
• Example:
if (user < 18) {
[Link]("You are a minor.");
} else if (user >= 18 && user <= 39) {
[Link]("You are a young adult.");
} else {
[Link]("You are an adult.");
6. Nested IF Statements
• You can place one if statement inside another to check multiple conditions.
• Example:
if (user < 19) {
if (user >= 16) {
[Link]("You are a young teenager.");
} else {
[Link]("You are a child.");
Boolean Values & Logical Operators
• Boolean values can only be true or false.
• Logical Operators:
o &&: AND — Both conditions must be true.
o ||: OR — At least one condition must be true.
o !: NOT — Reverses the condition.
• Example:
if (user == true) {
[Link]("User is verified.");
if (!user) {
[Link]("User is not verified.");
SWITCH Statements
• A switch statement is an alternative to a long series of if…else if statements. It checks a
variable against multiple values.
• Example:
switch (userAge) {
case 18:
[Link]("You are 18 years old.");
break;
case 19:
[Link]("You are 19 years old.");
break;
case 20:
[Link]("You are 20 years old.");
break;
default:
[Link]("Age not recognized.");
Key Concepts:
• Conditional logic: Helps control the flow of a program based on conditions.
• IF, ELSE, ELSE IF: Used for binary or multiple choices.
• SWITCH: Simplifies conditions when there are many possible values to check.
Example Applications:
1. IF Statements:
Check if a student has passed:
int score = 85;
if (score >= 75) {
[Link]("Student passed.");
IF…ELSE Statements:
Check if the temperature is hot or cold:
int temperature = 30;
if (temperature > 25) {
[Link]("It is hot.");
} else {
[Link]("It is cold.");
}
Switch Statements:
Assign a grade based on score:
int score = 85;
switch (score / 10) {
case 10:
case 9:
[Link]("Grade: A");
break;
case 8:
[Link]("Grade: B");
break;
case 7:
[Link]("Grade: C");
break;
default:
[Link]("Grade: F");