Java Programming - Lesson 7
Java Conditional Statements Explained: If, Else, Else-If and Switch
Introduction
A computer programme often needs to make decisions.
For example, a school management system may need to determine whether a student has passed an examination. A banking application may need to check whether an account has sufficient funds before processing a withdrawal. An online store may need to decide whether a customer qualifies for a discount.
How does a Java programme make such decisions?
The answer lies in conditional statements.
Conditional statements allow a programme to evaluate conditions and choose which instructions to execute based on the results.
In this tutorial, you will learn how to use Java's if, if-else, else-if, and switch statements. You will also learn about logical fall-through in traditional switch statements and practise applying these concepts through simple programming exercises.
Let's get started!
1. What Are Conditional Statements?
A conditional statement is a programming structure that allows a programme to execute different instructions depending on whether a condition is true or false.
For example, consider this statement:
int age = 20;
if (age >= 18) {
System.out.println("You are an adult.");
}
The programme checks whether age is greater than or equal to 18.
Since the value of age is 20, the condition is true, and the message is displayed.
If the age were 15, the condition would be false, and the message would not appear.
Conditional statements make programmes more intelligent and responsive because they allow the execution of code to depend on the data being processed.
2. Understanding the If Statement
The if statement is one of the simplest conditional structures in Java.
It executes a block of code only when a specified condition evaluates to true.
Syntax
if (condition) {
// Statements executed when the condition is true
}
The condition must evaluate to a Boolean value: true or false.
Example
public class IfExample {
public static void main(String[] args) {
int a = 99;
int b = 100;
if (a < b) {
System.out.println(a + " is less than " + b);
}
}
}
Output
99 is less than 100
The condition is:
a < b
The less-than operator checks whether the value of a is smaller than the value of b.
Because 99 is less than 100, the statement inside the if block executes.
What Happens When the Condition Is False?
Consider the following modification:
int a = 199;
int b = 100;
if (a < b) {
System.out.println(a + " is less than " + b);
}
The condition is false because 199 is not less than 100.
Consequently, the if block does not execute, and nothing is printed by this section of the programme.
This behaviour is useful when an action should occur only when a particular requirement is satisfied.
3. The If-Else Statement
What if we want the programme to do something when the condition is false?
We can use an else clause.
Syntax
if (condition) {
// Executes if the condition is true
} else {
// Executes if the condition is false
}
Example
public class IfElseExample {
public static void main(String[] args) {
int a = 199;
int b = 100;
if (a < b) {
System.out.println("A is less than B");
} else {
System.out.println("A is not less than B");
}
}
}
Output
A is not less than B
Since the condition is false, Java executes the else block.
The if and else blocks provide two alternative paths through the programme.
Only one of the two blocks executes in this example.
A Practical Example: Pass or Fail
Suppose a student must score at least 50 marks to pass an examination.
We can write:
int score = 65;
if (score >= 50) {
System.out.println("Congratulations! You passed.");
} else {
System.out.println("You did not pass.");
}
Output:
Congratulations! You passed.
If the score were 40, the second message would appear instead.
This is a simple illustration of how conditional statements can be used in an educational application.
4. Understanding Else-If Statements
Sometimes, a programme must choose among more than two alternatives.
For example, a grading system might classify results as excellent, good, pass or fail.
Writing a separate, unrelated if statement for every possibility may produce confusing or incorrect results. An if-else-if chain allows the programme to test conditions in sequence.
Syntax
if (condition1) {
// First alternative
} else if (condition2) {
// Second alternative
} else if (condition3) {
// Third alternative
} else {
// Default alternative
}
Java evaluates the conditions from top to bottom.
When one condition is true, its block executes, and the remaining branches in that chain are skipped.
Example: A Simple Grading System
public class GradeExample {
public static void main(String[] args) {
int score = 75;
if (score >= 80) {
System.out.println("Excellent");
} else if (score >= 60) {
System.out.println("Good");
} else if (score >= 40) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
Output:
Good
The programme checks whether the score is at least 80. Since 75 is less than 80, that condition is false.
It then checks whether the score is at least 60. This condition is true, so the programme displays Good.
The remaining conditions are not evaluated as part of this chain.
Important: The order of conditions matters. In grading systems, place the highest thresholds first so that a higher score is not incorrectly classified by a broader, lower threshold.
5. Understanding Comparison Operators
Conditional statements frequently use comparison operators.
These operators compare values and produce a Boolean result.
Operator
Meaning
Example
==
Equal to
a == b
!=
Not equal to
a != b
>
Greater than
a > b
<
Less than
a < b
>=
Greater than or equal to
a >= b
<=
Less than or equal to
a <= b
For example:
int a = 10;
int b = 20;
System.out.println(a < b);
System.out.println(a == b);
System.out.println(a != b);
Output:
true
false
true
Understanding these operators is essential because they determine whether the branches of conditional statements execute.
A Common Beginner's Mistake
Do not confuse:
a = 10;
with:
a == 10
The first assigns a value to a variable. The second checks whether two values are equal.
In a conditional expression, use == when you intend to compare primitive values for equality.
6. The Switch Statement
Java's switch statement provides another way to select among multiple alternatives.
It is especially useful when one expression needs to be compared with several possible case labels.
Syntax
switch (expression) {
case value1:
// Statements
break;
case value2:
// Statements
break;
default:
// Statements when no case matches
}
The switch expression is evaluated, and execution begins at the matching case label.
For the traditional switch form used in this lesson, a break statement normally prevents execution from continuing into the following cases.
The default branch provides an alternative when no case matches.
Example
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
default:
System.out.println("Unknown day");
}
}
}
Output:
Wednesday
Because the value of day is 3, Java selects case 3 and displays Wednesday.
The break statement then exits the switch.
7. Understanding the Default Branch
The default branch executes when no case label matches the switch expression.
Consider:
int choice = 9;
switch (choice) {
case 1:
System.out.println("Start");
break;
case 2:
System.out.println("Settings");
break;
case 3:
System.out.println("Exit");
break;
default:
System.out.println("Invalid choice");
}
Output:
Invalid choice
The value nine does not match any of the specified cases, so the default branch executes.
A default branch is optional, but including one is often useful when the programme needs to handle unexpected or unsupported values.
8. Using Multiple Case Labels for the Same Action
Sometimes, different values should produce the same result.
For example, a programme may need to classify several menu choices under one category.
Java allows multiple case labels to share the same block.
int a = 99;
switch (a) {
case 98:
case 99:
System.out.println("A is 98 or 99");
break;
case 100:
System.out.println("A is 100");
break;
default:
System.out.println("A is something else");
}
Output:
A is 98 or 99
The labels case 98 and case 99 lead to the same statement.
When a equals 99, execution begins at case 99, and the shared message is displayed.
When a equals 98, execution begins at case 98 and continues to the same message.
This technique is often described as grouping cases.
9. Understanding Fall-Through in Traditional Switch Statements
One of the most important features to understand about the traditional switch statement is fall-through.
Fall-through occurs when execution continues into subsequent case sections because a break statement is absent.
Consider:
int a = 98;
switch (a) {
case 98:
System.out.println("A is 98");
case 99:
System.out.println("A is 99");
break;
case 100:
System.out.println("A is 100");
break;
}
Output:
A is 98
A is 99
Why are both messages displayed?
The value 98 matches case 98, so execution begins there.
After printing A is 98, the programme encounters no break statement. Execution therefore continues into case 99.
The second message is printed before the break terminates the switch.
If we also removed the break after case 99, execution would continue into case 100.
This behaviour can be intentional, but it can also cause bugs when the programmer expects only one case to execute.
Practical advice: When using the traditional switch statement, include break after each case unless you deliberately want fall-through.
A Note About Modern Java
Modern Java also supports switch expressions and arrow-style switch rules, which have different syntax and control-flow behaviour.
For example:
int day = 3;
String dayName = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Other day";
};
System.out.println(dayName);
Output:
Wednesday
This modern form avoids the traditional fall-through behaviour between arrow-style rules.
The examples in the main tutorial use the traditional switch statement because it matches the lesson's teaching approach.
10. Choosing Between If-Else and Switch
Both if-else and switch allow a programme to choose between alternatives, but they are not identical.
An if-else chain is particularly useful when conditions involve ranges, comparisons or combinations of Boolean expressions.
For example:
int temperature = 35;
if (temperature >= 35) {
System.out.println("Very hot");
} else if (temperature >= 25) {
System.out.println("Warm");
} else {
System.out.println("Cool");
}
A switch statement is useful when selecting among distinct values.
For example:
int option = 2;
switch (option) {
case 1:
System.out.println("Create account");
break;
case 2:
System.out.println("Sign in");
break;
default:
System.out.println("Invalid option");
}
A simple guideline is:
Use if-else for ranges and complex conditions.
Use switch when selecting among distinct alternatives based on a single expression.
The best choice depends on the clarity and requirements of the programme.
11. Practical Exercises
Now that you understand the fundamental concepts, try these exercises.
Exercise 1: Positive or Negative
Write a Java programme that checks whether an integer is positive, negative or zero.
Hint: Use an if-else-if chain.
Exercise 2: Even or Odd
Write a programme that determines whether an integer is even or odd.
Hint: Use the remainder operator %.
An integer is even when:
number % 2 == 0
Exercise 3: Student Grades
Create a programme that accepts a student's score and displays a grade according to these rules:
80–100: Excellent
60–79: Good
40–59: Pass
Below 40: Fail
For this exercise, assume the score is within the valid range of zero to one hundred.
Exercise 4: Simple Calculator Menu
Use a switch statement to display an appropriate message for these options:
1: Addition
2: Subtraction
3: Multiplication
4: Division
Display Invalid choice for any other value.
Exercise 5: Understanding Fall-Through
Study this code:
int number = 2;
switch (number) {
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
case 3:
System.out.println("Three");
break;
default:
System.out.println("Other");
}
Determine the output before running the programme.
Then add the appropriate break statements and compare the results.
Conclusion
Conditional statements are among the most important foundations of Java programming.
They allow programmes to evaluate conditions, make decisions and respond differently to changing values.
In this tutorial, we explored the if, if-else, else-if, and switch statements. We also learned about comparison operators, default br
anches, grouped case labels and fall-through in traditional switch statements.
As you continue learning Java, practise writing conditions for everyday situations, such as calculating grades, validating user choices and determining eligibility.
With regular practice, you will become more confident in designing programmes that make decisions logically and reliably.
Watch the accompanying video tutorial via the link below:
https://youtu.be/qmENDrgqfQU?si=zIK2iPqJnJF0I0cp
Creative Skills & Hobbies Hub – Where Creativity, Knowledge, and Inspiration Thrive!


Comments
Post a Comment
Welcome to Creative Skills & Hobbies Hub!
This blog is dedicated to recognizing, showcasing, and promoting diverse creative skills and hobbies, with the aim of helping individuals discover and nurture their own creative potentials, etc. We encourage you to share your thoughts, ask questions, and engage with our community.
Your voice matters! Whether you have a new hobby to explore, insights to offer, or creative stories to tell, we’d love to hear from you. Leave a comment below and join the conversation!