Day 6: Understanding Java’s if, else if, and else Statements
Source: Dev.to
What Are Conditional Statements?
Conditional statements in Java are used to control the flow of a program only when a condition is true. This is very useful when a program needs to behave differently for different inputs.
The if Statement
The if statement checks a condition inside parentheses.
- If the condition is true, the code inside the block runs.
- If the condition is false, the code is skipped.
Example
int score = 60;
if (score >= 50) {
System.out.println("You passed the exam!");
}
The else if Statement
The else if statement is used to check another condition when the first if condition is false.
Example
int score = 75;
if (score >= 90) {
System.out.println("Excellent!");
} else if (score >= 50) {
System.out.println("You passed.");
}
The else Statement
The else statement runs when none of the above conditions are true.
Example
int score = 40;
if (score >= 90) {
System.out.println("Excellent!");
} else if (score >= 50) {
System.out.println("You passed.");
} else {
System.out.println("You failed.");
}
Simple Rule to Remember
if→ checks the first conditionelse if→ checks additional conditionselse→ runs when all conditions are false
Only one block executes in an if–else if–else structure.
Task Assigned for the Day
Set the account balance as 5000.
- If the balance is below 5000, display:
"Withdrawal successfully" - If the balance is more than 5000, display:
"Withdrawal Failed"
Sample Code
package demo;
public class Sample {
public static void main(String[] args) {
int balance = 4500;
if (balance > 5000) {
System.out.println("Withdrawal Failed!");
} else {
System.out.println("Withdrawal successfull");
}
}
}
Explanation
balanceis currently set to4500.- Since the balance is less than
5000, the program prints “Withdrawal successfull”. - If the balance were greater than
5000, it would print “Withdrawal Failed!”.