Java Learner logo

Module 3: Control Flow and Decision Making

Lesson focus

Conditional Logic: If, Else If, and Else Statements

Learn to execute different blocks of code based on boolean conditions, allowing your program to react dynamically to different situations.

Making Decisions in Code: Often, you need your program to do different things based on certain conditions. This is called conditional logic, and the most fundamental tool for it is the if statement.

The if Statement: The if statement executes a block of code only if its condition evaluates to true.

  • Syntax: if (condition) { // code to execute if true }
  • The condition must be a boolean expression (something that results in true or false).

The else Statement: The else statement provides a block of code to execute if the if condition is false. It acts as a default or fallback action.

  • Syntax: if (condition) { ... } else { // code to execute if false }

The else if Statement: To check multiple conditions in a sequence, you can use else if. Java will check the conditions one by one. The first one that is true will have its code block executed, and the rest of the chain will be skipped.

  • Syntax: if (condition1) { ... } else if (condition2) { ... } else { ... }

Best Practices:

  • Use Curly Braces: Always use curly braces {} to enclose the code block for an if, else if, or else statement, even if it's just a single line. This prevents common and hard-to-find bugs.
  • Order Matters: In an if-else if chain, order your conditions from most specific to most general if they overlap.

Mini-Exercise: Write a program that assigns a letter grade (A, B, C, D, F) based on a numerical score (0-100). Use an if-else if-else chain to handle the different score ranges (e.g., 90-100 is A, 80-89 is B, etc.).

int score = 85;
char grade;

if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else if (score >= 60) {
    grade = 'D';
} else {
    grade = 'F';
}

System.out.println("Your grade is: " + grade); // Your grade is: B

Lesson quiz

Given `int x = 10;`, which block of code will be executed?

Next lesson →