Conditional Statement - if-else Statement
Source: Dev.to
Conditional Statement / Decision Making Statement / Control Flow Statement – if‑else Statement
- The if‑else statement is used to make decisions in a program based on a boolean condition.
- It executes the code block only if the condition is true.
Core Conditional Statements
if Statement
The most basic form. It executes a block of code only if the specified condition is true.
if (age >= 18) {
System.out.println("You are an adult.");
}
if‑else Statement
Provides an alternative path. If the if condition is false, the else block executes.
if (marks >= 35) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
else‑if Ladder
Used to check multiple conditions. Once a true condition is found, its block runs, and the rest of the ladder is skipped.
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 35) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
Core Rules
- Boolean Condition Required: The condition within the
ifstatement parentheses()must be a boolean expression. Non‑boolean values (e.g., integers) cannot be used as conditions in Java. elseis Optional: Anifstatement can exist alone without anelseblock.- Curly Braces
{}: If theiforelseblock contains more than one statement, enclose them within curly braces{}. - Execution Flow: In an
if‑else‑ifladder, conditions are evaluated from top to bottom. As soon as a condition evaluates totrue, its corresponding block of code is executed, and the remaining conditions are skipped.