CHAPTER 07
Beginner
Conditional Statements
Updated: May 17, 2026
5 min read
# CHAPTER 7
Conditional Statements
1. Introduction
Programs need to make decisions. Should the ATM allow a withdrawal? Is the password correct? Is the student passing or failing? Conditional statements allow your program to choose different paths of execution based on conditions. This is the foundation of all intelligent software.2. Learning Objectives
-
Use
if,if-else, andelse ifstatements.
- Implement nested conditions.
-
Use the
switchstatement for multi-way branching.
- Build a grade evaluation system.
3. The if Statement
Executes a block of code only if the condition is true.
java
4. The if-else Statement
Provides an alternative path when the condition is false.
java
5. The else if Ladder
Tests multiple conditions sequentially.
java
6. Nested if Statements
An if inside another if.
java
7. The switch Statement
Ideal for comparing one variable against many exact values.
java
Important: Without break, execution "falls through" to the next case!
8. Enhanced Switch (Java 14+)
java
9. Mini Project: Grade Evaluation System
java
10. Common Mistakes
-
Using
=instead of==:if (x = 5)assigns;if (x == 5)compares.
-
Missing
breakin switch: Causes fall-through behavior.
-
Comparing Strings with
==: Use.equals()for String comparison.
11. Exercises
- 1. Write a program that checks if a number is positive, negative, or zero.
- 2. Build a simple calculator using switch-case (add, subtract, multiply, divide).
- 3. Write a program that takes a month number (1-12) and prints the season.
12. MCQ Quiz with Answers
Question 1
What keyword provides the default case in a switch?
Question 2
What happens without break in a switch case?
Question 3
Which operator is used for comparison?
Question 4
Can switch work with Strings?
Question 5
What does else if allow?
Question 6
What is the output of if(false) { print("A"); } else { print("B"); }?
Question 7
Can you nest if statements?
Question 8
How do you compare strings in Java?
Question 9
What does (x > 5 && x < 10) mean?
Question 10
Switch can work with which types?
13. Interview Questions
-
Q: What is the difference between
if-elseandswitch?
- Q: What is fall-through in switch? Is it ever useful?
-
Q: Why should you use
.equals()instead of==for Strings?
14. Summary
Conditional statements (if, else if, else, switch) enable decision-making in Java programs. The switch statement is cleaner for comparing one variable against many values. Always use .equals() for String comparisons and always include break in switch cases unless fall-through is intentional.
15. Next Chapter Recommendation
In Chapter 8: Loops in Java, we'll learn how to repeat actions usingfor, while, and do-while loops.