On Day 5, we learn about conditional statements, which allow a program to make decisions based on conditions. Instead of running all lines of code, Java can choose different paths depending on the situation. The three main forms are if, else if, and else.
1. The if Statement
The if
statement checks a condition. If it’s true, the block of code inside executes.
int age = 20;
if (age >= 18) {
System.out.println("You are an adult.");
}
How it works: Since age
is 20, the condition age >= 18
is true, so the message is printed.
2. The if-else Statement
If the if
condition is false, the else
block runs instead.
int age = 15;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
How it works: Here, age
is 15, so the condition is false. The program executes the else
part instead.
3. The if-else if-else Statement
When there are multiple conditions, we use else if
blocks to check them one by one.
int marks = 75;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 50) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
How it works: The program checks conditions from top to bottom. Since marks
is 75, the second condition is true, so Grade B
is printed. Once a condition is true, the rest are skipped.
Summary
Conditional statements are essential for decision-making in Java. They allow programs to behave differently depending on the input or situation. With if
, else if
, and else
, you can build powerful logic that controls the program flow.