Lesson 15 of 140
Written lesson · 14 min

Conditional Statements

Make decisions with `if`, `else if` and `else`, combine conditions, check numeric ranges and avoid common mistakes in conditional logic.

Preview

You are viewing a free preview lesson.

Lesson Overview

So far, our programs have run every statement from top to bottom. Real programs must decide: allow enrollment only if the learner is 18 or older, show "Passed" only if the mark is 40 or above, allow login only if both email and password are valid.

In Java, conditional statements control which code runs based on conditions. Writing a condition is easy; writing the right one, in the right order, with the right operator, is where most beginner bugs live, so this lesson spends as much time on those mistakes as on the syntax.

Learning Objectives

After completing this lesson, you will be able to:

  • Make decisions using boolean expressions
  • Write if, if-else, and else-if
  • Distinguish between independent and mutually exclusive conditions
  • Combine multiple conditions
  • Validate numeric ranges
  • Understand nested conditions
  • Identify common mistakes in conditional logic
  • Create simple decision-making programs

What Is Conditional Execution?

Conditional execution means executing or skipping a block of code depending on the result of a condition.

java
int age = 20;
if (age >= 18) {
    System.out.println("Adult");
}

The condition age >= 18 is true, so the block executes.

Output:

text
Adult

If age is 15, the condition is false and the block does not execute.

A Condition Must Be Boolean

The result of a condition in a Java conditional statement must be true or false. Valid conditions:

java
age >= 18
score == 100
isActive
!accountBlocked
emailValid && passwordValid

In Java, a number cannot be used directly as a condition. Invalid:

java
int value = 1;
if (value) {
    System.out.println("Valid");
}

Correct:

java
if (value == 1) {
    System.out.println("Value is one");
}

if Statement

Syntax:

java
if (condition) {
    // Executes when condition is true
}

Example:

java
int mark = 75;
if (mark >= 40) {
    System.out.println("Passed");
}

Output:

text
Passed

If the condition is false, the block is skipped. A block can also hold several statements; if the condition is true, they execute from top to bottom:

java
int age = 20;
if (age >= 18) {
    System.out.println("Age requirement met");
    System.out.println("Enrollment allowed");
}

Use Curly Braces

Curly braces can technically be omitted for a single statement:

java
if (age >= 18)
    System.out.println("Adult");

However, using braces is safer and clearer. Preferred:

java
if (age >= 18) {
    System.out.println("Adult");
}

This reduces the risk of accidentally breaking the logic when another statement is added later.

if-else

Use if-else when different branches are needed for both the true and false cases. Only one branch executes during a single execution.

java
int mark = 35;
if (mark >= 40) {
    System.out.println("Passed");
} else {
    System.out.println("Failed");
}

Output:

text
Failed

Example: Even or Odd

java
int number = 17;
if (number % 2 == 0) {
    System.out.println("Even");
} else {
    System.out.println("Odd");
}

Output:

text
Odd

else-if

When there are more than two mutually exclusive outcomes, else-if can be used:

java
if (firstCondition) {
    // First branch
} else if (secondCondition) {
    // Second branch
} else {
    // Default branch
}

Java checks conditions from top to bottom. After the first true branch executes, the remaining branches are skipped.

Positive, Negative, or Zero

java
int number = -10;
if (number > 0) {
    System.out.println("Positive");
} else if (number < 0) {
    System.out.println("Negative");
} else {
    System.out.println("Zero");
}

Output:

text
Negative

Condition Order Is Important

Look at this code:

java
int mark = 90;
if (mark >= 40) {
    System.out.println("Passed");
} else if (mark >= 80) {
    System.out.println("Excellent");
}

Output:

text
Passed

mark >= 40 is already true, so the next condition is never checked. Better:

java
if (mark >= 80) {
    System.out.println("Excellent");
} else if (mark >= 40) {
    System.out.println("Passed");
} else {
    System.out.println("Failed");
}

When conditions overlap, the more specific condition or higher threshold should generally be checked first.

Grade Example

This program reads a mark (as in lesson 1.14) and selects exactly one grade. The first check rejects marks outside 0 to 100; the rest go from the highest threshold down:

java
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your mark: ");
        int mark = Integer.parseInt(scanner.nextLine().strip());

        if (mark < 0 || mark > 100) {
            System.out.println("Invalid mark");
        } else if (mark >= 80) {
            System.out.println("Grade: A");
        } else if (mark >= 70) {
            System.out.println("Grade: B");
        } else if (mark >= 60) {
            System.out.println("Grade: C");
        } else if (mark >= 50) {
            System.out.println("Grade: D");
        } else if (mark >= 40) {
            System.out.println("Grade: E");
        } else {
            System.out.println("Grade: F");
        }

        scanner.close();
    }
}

Possible interaction:

text
Enter your mark: 85
Grade: A

Because else-if is used, only one grade is selected for a mark.

Why Do We Not Repeat the Upper Bound?

Look at this section:

java
if (mark >= 80) {
    grade = "A";
} else if (mark >= 70) {
    grade = "B";
}

The second condition is checked only when mark < 80. Therefore, mark >= 70 effectively represents 70 <= mark < 80.

Multiple Independent if Statements

Not all conditions are mutually exclusive:

java
int mark = 90;
if (mark >= 40) {
    System.out.println("Passed");
}

if (mark >= 80) {
    System.out.println("Distinction");
}

Output:

text
Passed
Distinction

Both conditions are independently true.

When Should You Use Each?

With multiple if statements, several blocks may execute; with else-if, only the first matching branch does. Use separate if statements for independent results:

java
if (mark >= 40) {
    System.out.println("Passed");
}

if (mark >= 80) {
    System.out.println("Scholarship eligible");
}

Use else-if for mutually exclusive results:

java
if (mark >= 80) {
    System.out.println("A");
} else if (mark >= 70) {
    System.out.println("B");
} else {
    System.out.println("C or below");
}

Logical Operators in Conditions

Multiple Conditions with &&

When every condition must be true, use &&. Here, age must be at least 18 and email must be verified; both must be true:

java
int age = 20;
boolean emailVerified = true;
if (age >= 18 && emailVerified) {
    System.out.println("Enrollment allowed");
}

Alternative Conditions with ||

When at least one condition must be true:

java
boolean isInstructor = false;
boolean isAdmin = true;
if (isInstructor || isAdmin) {
    System.out.println("Access allowed");
}

Output:

text
Access allowed

Reverse a Condition with !

Here, the result of !accountBlocked is true:

java
boolean accountBlocked = false;
if (!accountBlocked) {
    System.out.println("Account access allowed");
}

Keep Complex Conditions Readable

java
int age = 20;
boolean emailVerified = true;
boolean accountBlocked = false;
boolean enrollmentOpen = true;
boolean canEnroll =
        age >= 18 && emailVerified && !accountBlocked && enrollmentOpen;
if (canEnroll) {
    System.out.println("Enrollment allowed");
}

A meaningful boolean variable can make a complex condition easier to understand.

Range Validation

Suppose a mark is valid from 0 to 100. The valid and invalid checks are:

java
boolean validMark = mark >= 0 && mark <= 100;
boolean invalidMark = mark < 0 || mark > 100;

Wrong Range Logic

Wrong:

java
boolean validMark = mark >= 0 || mark <= 100;

Suppose mark = 500. Then:

text
500 >= 0   → true
500 <= 100 → false
true || false → true

500 would incorrectly be considered valid. Correct: mark >= 0 && mark <= 100.

Mathematical Chained Comparisons Are Not Valid in Java

In mathematics, you may write 0 <= mark <= 100, but this is not valid Java:

java
if (0 <= mark <= 100) {
}

Correct:

java
if (mark >= 0 && mark <= 100) {
    System.out.println("Valid mark");
}

Nested if

A conditional statement inside another conditional block is called a nested if. The inner condition is evaluated only if the outer condition is true.

java
int age = 20;
boolean emailVerified = true;
if (age >= 18) {
    if (emailVerified) {
        System.out.println("Enrollment allowed");
    }
}

A nested condition can be useful when the second decision depends on the context established by the first decision:

java
boolean loggedIn = true;
boolean isAdmin = false;
if (loggedIn) {
    if (isAdmin) {
        System.out.println("Admin dashboard");
    } else {
        System.out.println("User dashboard");
    }
} else {
    System.out.println("Please log in");
}

However, avoid unnecessary deep nesting.

Showing a Specific Failure Reason

Sometimes it is useful to show a specific failure reason instead of combining everything into one success condition. Here, the conditions are ordered according to the user flow:

java
boolean userExists = true;
boolean passwordCorrect = false;
boolean accountLocked = false;
if (!userExists) {
    System.out.println("User not found");
} else if (!passwordCorrect) {
    System.out.println("Incorrect password");
} else if (accountLocked) {
    System.out.println("Account is locked");
} else {
    System.out.println("Login successful");
}

String Conditions

To compare String content, use equals(), or equalsIgnoreCase() to ignore case:

java
String role = "ADMIN";
if ("ADMIN".equals(role)) {
    System.out.println("Access allowed");
}

if ("ADMIN".equalsIgnoreCase(role)) {
    System.out.println("Access allowed");
}

For String content, do not use role == "ADMIN".

null and String Check

java
String courseName = null;
if (courseName != null && !courseName.isBlank()) {
    System.out.println("Valid course name");
} else {
    System.out.println("Course name is required");
}

If courseName is null, the first condition is false. Because of short-circuit evaluation, courseName.isBlank() will not be called.

Complete Example: Enrollment Decision

java
public class Main {

    public static void main(String[] args) {
        int learnerAge = 20;
        boolean emailVerified = true;
        boolean enrollmentOpen = true;
        boolean accountBlocked = false;

        if (learnerAge < 0) {
            System.out.println("Invalid age");
        } else if (learnerAge < 18) {
            System.out.println("Minimum age requirement not met");
        } else if (!emailVerified) {
            System.out.println("Email verification required");
        } else if (!enrollmentOpen) {
            System.out.println("Enrollment is closed");
        } else if (accountBlocked) {
            System.out.println("Blocked account cannot enroll");
        } else {
            System.out.println("Enrollment allowed");
        }
    }
}

Output:

text
Enrollment allowed

Test Boundary Values

When testing conditional logic, do not test only normal values. Also test values around the boundaries where a condition changes. This helps identify off-by-one and incorrect condition-order bugs:

  • For the rule age >= 18, test 17, 18 and 19.
  • For a mark range of 0 to 100, test -1, 0, 1, 99, 100 and 101.
  • For grade boundaries, test 39, 40, 69, 70, 79 and 80.

Predict the Result

Question 1

java
int mark = 92;
if (mark >= 50) {
    System.out.println("Pass");
} else if (mark >= 90) {
    System.out.println("Excellent");
}

What does this print?

Answer

Pass. An if-else-if chain runs only the first branch whose condition is true. mark >= 50 is checked first and is true, so mark >= 90 is never checked. The stricter condition must come first.

Question 2

java
int mark = 92;
if (mark >= 50) {
    System.out.println("Pass");
}
if (mark >= 90) {
    System.out.println("Excellent");
} else {
    System.out.println("Keep going");
}

What does this print?

Answer

text
Pass
Excellent

These are two independent if statements, so both are checked. The else belongs only to the second one.

Question 3

java
int age = 16;
boolean hasPermission = true;
if (age >= 18 || hasPermission) {
    System.out.println("Can enroll");
} else {
    System.out.println("Cannot enroll");
}

What does this print?

Answer

Can enroll. With ||, one true side is enough. age >= 18 is false, but hasPermission is true.

Question 4

java
int mark = 105;
if (mark >= 0 || mark <= 100) {
    System.out.println("Valid");
} else {
    System.out.println("Invalid");
}

What does this print?

Answer

Valid, which is wrong. Every number is either at least 0 or at most 100, so this condition is always true. A range check needs &&: mark >= 0 && mark <= 100.

Question 5

java
int mark = 75;
if (mark) {
    System.out.println("Has a mark");
}

Will it compile?

Answer

No: incompatible types: int cannot be converted to boolean. A condition must be a boolean; Java does not treat numbers as true or false. Write a comparison such as mark > 0.

Common Mistakes

Extra Semicolon After if

Wrong:

java
if (age >= 18); {
    System.out.println("Adult");
}

The semicolon has already ended the if statement. Correct:

java
if (age >= 18) {
    System.out.println("Adult");
}

Assignment Instead of Comparison

Wrong:

java
boolean active = false;
if (active = true) {
    System.out.println("Active");
}

This performs assignment instead of comparison. active becomes true, so the block always executes. Preferred:

java
if (active) {
    System.out.println("Active");
}

Comparing a Boolean with == true

Verbose:

java
if (isAvailable == true) {
}

Preferred, followed by the false check:

java
if (isAvailable) {
}

if (!isAvailable) {
}

Multiple if Statements for Exclusive Results

Wrong:

java
if (mark >= 80) {
    System.out.println("A");
}

if (mark >= 70) {
    System.out.println("B");
}

if (mark >= 60) {
    System.out.println("C");
}

If mark = 85, all three outputs appear. Correct:

java
if (mark >= 80) {
    System.out.println("A");
} else if (mark >= 70) {
    System.out.println("B");
} else if (mark >= 60) {
    System.out.println("C");
}

Practice Exercise 1: Even or Odd

Solutions: lesson 1.24.

Take an integer and print Even or Odd.

Practice Exercise 2: Positive, Negative, or Zero

For an integer, determine whether it is Positive, Negative or Zero.

Practice Exercise 3: Valid Mark

A mark is valid from 0 to 100. Write a boolean expression and print the result.

Practice Exercise 4: Grade Calculator

Rules:

text
80–100 → A
70–79  → B
60–69  → C
50–59  → D
40–49  → E
0–39   → F

Handle invalid marks.

Practice Exercise 5: Login Decision

java
boolean userExists = true;
boolean passwordCorrect = false;
boolean accountLocked = false;

Show a specific result:

  • User not found
  • Incorrect password
  • Account locked
  • Login successful

Practice Exercise 6: Enrollment Eligibility

Rules:

  • Minimum age 18
  • Email verified
  • Enrollment open
  • Account is not blocked

Use else-if to show a specific failure reason.

Practice Exercise 7: Multiple Independent Conditions

For a mark, independently check:

  • Whether the student passed (passing mark 40)
  • Whether the student received distinction (80)

Practice Exercise 8: Boundary Testing

For the grade calculator, test 39, 40, 69, 70, 79, 80, 100 and 101. Write the expected result for each input.

Knowledge Check

Question 1

What is conditional execution?

Question 2

What type must the result of an if condition be?

Question 3

When does an if block execute?

Question 4

When does else execute?

Question 5

How many branches can execute in an else-if chain?

Question 6

Can multiple independent if blocks execute?

Question 7

Why is condition order important?

Question 8

What expression checks whether a mark is within 0–100?

Question 9

What expression checks whether a mark is outside the valid range?

Question 10

What do &&, ||, and ! do?

Question 11

What is a nested if?

Question 12

Which method should be used to compare String content?

Question 13

Why is name != null && !name.isBlank() safe?

Question 14

Why is boundary value testing useful?

Knowledge Check Answers

Answer 1

Conditional execution means executing or skipping code depending on the result of a condition.

Answer 2

boolean

Answer 3

When the condition is true.

Answer 4

When the associated if and previous else-if conditions are false.

Answer 5

At most one matching branch executes.

Answer 6

Yes.

Answer 7

An else-if chain is evaluated from top to bottom, and after the first matching branch executes, the remaining branches are skipped.

Answer 8

mark >= 0 && mark <= 100

Answer 9

mark < 0 || mark > 100

Answer 10

  • && — all conditions must be true
  • || — at least one condition must be true
  • ! — reverses a boolean value

Answer 11

A conditional statement inside another conditional block.

Answer 12

equals(), or equalsIgnoreCase() for case-insensitive comparison.

Answer 13

If name is null, the first condition becomes false and short-circuit evaluation prevents isBlank() from being called.

Answer 14

Boundary value testing helps detect incorrect comparisons and off-by-one errors near the points where conditions change.

Lesson Summary

  • A conditional statement executes or skips code depending on a condition, and the condition must be a boolean.
  • if runs a block when its condition is true, and if-else chooses between two branches.
  • In an else-if chain, Java checks conditions from top to bottom and runs only the first matching branch.
  • When conditions overlap, check the more specific condition or higher threshold first.
  • Use multiple independent if statements when more than one result can apply.
  • Combine conditions with &&, || and !, and write a range check as mark >= 0 && mark <= 100.
  • Compare String content with equals(), and check for null before calling a method on a String.
  • Test boundary values around the points where a condition changes.

Think first

Coming soon

Checkpoint questions that ask you to commit to an answer before the lesson shows it.