Programming and Java Fundamentals
Conditional Statements
আপনি একটি free preview lesson দেখছেন।
Lesson Overview
A program does not always execute the same instructions.
Often, a program needs to make decisions based on data or conditions.
For example:
- Allow enrollment if age is
18or above - Show passed if a mark is
40or above - Accept an order if stock is available
- Determine whether a number is positive, negative, or zero
- Allow login if both email and password are valid
In Java, conditional statements are used to control execution flow based on conditions.
In this lesson, we will learn:
- Boolean conditions
ifif-elseelse-if- Multiple independent
ifstatements - Logical operators in conditions
- Range validation
- Nested conditions
- Common conditional mistakes
Learning Objectives
After completing this lesson, you will be able to:
- Make decisions using boolean expressions
- Write
if,if-else, andelse-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.
int age = 20;
if (age >= 18) {
System.out.println("Adult");
}
Condition:
age >= 18
Result:
true
Therefore, the block executes.
Output:
Adult
If:
int age = 15;
then 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:
age >= 18
score == 100
isActive
!accountBlocked
emailValid && passwordValid
In Java, a number cannot be used directly as a condition.
Invalid:
int value = 1;
if (value) {
System.out.println("Valid");
}
Correct:
if (value == 1) {
System.out.println("Value is one");
}
if Statement
Syntax:
if (condition) {
// Executes when condition is true
}
Example:
int mark = 75;
if (mark >= 40) {
System.out.println("Passed");
}
Output:
Passed
If the condition is false, the block is skipped.
Multiple Statements Inside an if Block
int age = 20;
if (age >= 18) {
System.out.println("Age requirement met");
System.out.println("Enrollment allowed");
}
If the condition is true, the statements inside the block execute from top to bottom.
Use Curly Braces
Curly braces can technically be omitted for a single statement:
if (age >= 18)
System.out.println("Adult");
However, using braces is safer and clearer.
Preferred:
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.
int mark = 35;
if (mark >= 40) {
System.out.println("Passed");
} else {
System.out.println("Failed");
}
Output:
Failed
Only one branch executes during a single execution.
Example: Even or Odd
int number = 17;
if (number % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
Output:
Odd
else-if
When there are more than two mutually exclusive outcomes, else-if can be used.
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
int number = -10;
if (number > 0) {
System.out.println("Positive");
} else if (number < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
Output:
Negative
Condition Order Is Important
Look at this code:
int mark = 90;
if (mark >= 40) {
System.out.println("Passed");
} else if (mark >= 80) {
System.out.println("Excellent");
}
Output:
Passed
mark >= 40 is already true, so the next condition is never checked.
Better:
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
int mark = 85;
String grade;
if (mark < 0 || mark > 100) {
grade = "Invalid";
} else if (mark >= 80) {
grade = "A";
} else if (mark >= 70) {
grade = "B";
} else if (mark >= 60) {
grade = "C";
} else if (mark >= 50) {
grade = "D";
} else if (mark >= 40) {
grade = "E";
} else {
grade = "F";
}
System.out.println(
"Grade: " + grade
);
Output:
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:
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.
int mark = 90;
if (mark >= 40) {
System.out.println("Passed");
}
if (mark >= 80) {
System.out.println("Distinction");
}
Output:
Passed
Distinction
Both conditions are independently true.
Multiple if vs. else-if
Multiple if
if (conditionA) {
}
if (conditionB) {
}
Multiple blocks may execute.
else-if
if (conditionA) {
} else if (conditionB) {
}
Only the first matching branch executes.
When Should You Use Each?
Independent results:
if (mark >= 40) {
System.out.println("Passed");
}
if (mark >= 80) {
System.out.println("Scholarship eligible");
}
Mutually exclusive results:
if (mark >= 80) {
System.out.println("A");
} else if (mark >= 70) {
System.out.println("B");
} else {
System.out.println("C or below");
}
Multiple Conditions with &&
When every condition must be true:
int age = 20;
boolean emailVerified = true;
if (age >= 18 && emailVerified) {
System.out.println("Enrollment allowed");
}
Here:
- Age must be at least
18 - Email must be verified
Both must be true.
Alternative Conditions with ||
When at least one condition must be true:
boolean isInstructor = false;
boolean isAdmin = true;
if (isInstructor || isAdmin) {
System.out.println("Access allowed");
}
Output:
Access allowed
Reverse a Condition with !
boolean accountBlocked = false;
if (!accountBlocked) {
System.out.println("Account access allowed");
}
The result of:
!accountBlocked
is:
true
Keep Complex Conditions Readable
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
Correct:
boolean validMark =
mark >= 0
&& mark <= 100;
Invalid mark:
boolean invalidMark =
mark < 0
|| mark > 100;
Wrong Range Logic
Wrong:
boolean validMark =
mark >= 0
|| mark <= 100;
Suppose:
mark = 500
Then:
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:
if (0 <= mark <= 100) {
}
Correct:
if (
mark >= 0
&& mark <= 100
) {
System.out.println("Valid mark");
}
Nested if
A conditional statement inside another conditional block is called a nested if.
int age = 20;
boolean emailVerified = true;
if (age >= 18) {
if (emailVerified) {
System.out.println(
"Enrollment allowed"
);
}
}
The inner condition is evaluated only if the outer condition is true.
When Is a Nested Condition Useful?
A nested condition can be useful when the second decision depends on the context established by the first decision.
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.
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");
}
Here, the conditions are ordered according to the user flow.
String Conditions
To compare String content:
String role = "ADMIN";
if ("ADMIN".equals(role)) {
System.out.println("Access allowed");
}
To ignore case:
if ("ADMIN".equalsIgnoreCase(role)) {
System.out.println("Access allowed");
}
For String content, do not use:
role == "ADMIN"
null and String Check
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.
Common Mistakes
Extra Semicolon After if
Wrong:
if (age >= 18); {
System.out.println("Adult");
}
The semicolon has already ended the if statement.
Correct:
if (age >= 18) {
System.out.println("Adult");
}
Assignment Instead of Comparison
Wrong:
boolean active = false;
if (active = true) {
System.out.println("Active");
}
This performs assignment instead of comparison.
Preferred:
if (active) {
System.out.println("Active");
}
Comparing a Boolean with == true
Verbose:
if (isAvailable == true) {
}
Preferred:
if (isAvailable) {
}
False check:
if (!isAvailable) {
}
Multiple if Statements for Exclusive Results
Wrong:
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 may appear.
Correct:
if (mark >= 80) {
System.out.println("A");
} else if (mark >= 70) {
System.out.println("B");
} else if (mark >= 60) {
System.out.println("C");
}
Wrong Null Check Order
Wrong:
if (
!name.isBlank()
&& name != null
) {
}
Correct:
if (
name != null
&& !name.isBlank()
) {
}
Complete Example: Enrollment Decision
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:
Enrollment allowed
Interactive Grade Program
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();
}
}
Test Boundary Values
When testing conditional logic, do not test only normal values. Also test values around the boundaries where a condition changes.
If the rule is:
age >= 18
Test:
17
18
19
For a mark range:
0 to 100
Test:
-1
0
1
99
100
101
For grade boundaries:
39
40
69
70
79
80
This helps identify off-by-one and incorrect condition-order bugs.
Important Terms
Conditional Statement
Controls execution flow based on a condition.
Condition
A boolean expression.
Branch
A possible execution path selected by a condition.
if
Executes a block when its condition is true.
else
Executes an alternative block when its associated condition is false.
else-if
Checks multiple mutually exclusive conditions.
Nested Condition
A conditional statement inside another conditional block.
Range Validation
Checks whether a value is within minimum and maximum boundaries.
Boundary Value
A test value near the point where a condition changes.
Practice Exercise 1: Even or Odd
Take an integer and print:
Even
or:
Odd
Practice Exercise 2: Positive, Negative, or Zero
For an integer, determine whether it is:
Positive
Negative
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:
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
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
- Whether the student received distinction
Passing mark:
40
Distinction:
80
Practice Exercise 8: Boundary Testing
For the grade calculator, test:
39
40
69
70
79
80
100
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()
For case-insensitive comparison:
equalsIgnoreCase()
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
In this lesson, we learned:
- Conditional statements control a program's execution path
- Conditions must produce boolean results
ifexecutes a block when its condition is trueif-elsehandles two alternative pathselse-ifhandles multiple mutually exclusive outcomes- After the first matching
else-ifbranch, the remaining branches are skipped - Condition order is important
- Multiple
ifstatements can be used for independent conditions &&,||, and!combine or reverse conditions- Numeric ranges can be validated using lower and upper boundaries
- Mathematical chained comparisons are not valid Java
- Nested
ifstatements can handle context-dependent decisions .equals()should be used to compare String content- A
nullcheck should happen before calling a method on a possibly null value - Extra semicolons and incorrect condition ordering are common bugs
- Testing boundary values is important for conditional logic