Back to course

Conditional Statements: if, else, and else if

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 10: Conditional Statements: if, else, and else if

Conditional statements allow your program to make decisions based on runtime conditions.

1. The if Statement

The if statement executes a block of code only if the condition inside the parentheses is true.

java int score = 85;

if (score > 80) { System.out.println("Excellent score!"); }

// Note: If the code block is only one line, curly braces are optional, // but using them is highly recommended for clarity and safety.

2. The if-else Statement

The if-else statement provides two paths: one for true and one for false.

java int temperature = 25;

if (temperature > 30) { System.out.println("It's very hot."); } else { System.out.println("The weather is mild."); }

3. The if-else if-else Ladder

When you need to check multiple sequential conditions, use the else if construct. Only one block will execute.

java int grade = 72; String message;

if (grade >= 90) { message = "Grade A"; } else if (grade >= 80) { message = "Grade B"; } else if (grade >= 70) { message = "Grade C"; } else { message = "Failing grade"; }

System.out.println(message); // Output: Grade C

4. The Ternary Operator

A shortcut for simple if-else statements. It takes three operands.

Syntax: condition ? expression_if_true : expression_if_false;

java int age = 22; String status = (age >= 18) ? "Adult" : "Minor"; System.out.println(status); // Output: Adult