Java Conditional Statements: if, if-else, else-if & Nested if
Why Conditions are Needed ยท if Statement ยท if-else ยท else-if Ladder ยท Nested if ยท Combining Logical Conditions (&&, ||, !)
Mastering decision-making and flow control in Java: understanding how boolean conditions direct program execution paths, building clean multi-way branching ladders with else-if, structuring nested decision trees, and combining complex logical criteria with short-circuit boolean operators.
1. Why are Conditions Needed in Programming?
By default, computer programs execute statements sequentially (line 1, then line 2, then line 3).
However, real-world software must make dynamic decisions based on runtime data:
- *If* a user enters the correct password, grant dashboard access; *otherwise*, lock the account.
- *If* an account balance is sufficient, process the withdrawal; *otherwise*, display "Insufficient Funds".
- *If* an e-commerce order exceeds โน1000, apply free shipping.
Conditional Statements allow your program to evaluate a boolean expression (true or false) and choose which branch of code to execute.
[ Start Evaluation ]
|
v
< Condition True? >
/ \
(Yes) / \ (No)
v v
[ Execute Block A ] [ Execute Block B ]
\ /
\ /
v v
[ Continue Program ]2. The 4 Forms of If-Branching in Java
1. Simple if Statement
Executes a block of code only if the specified condition evaluates to true:
if (age >= 18) {
System.out.println("Eligible to vote.");
}2. if-else Statement
Provides two mutually exclusive branches: executes the if block when true, or the else block when false:
if (balance >= withdrawAmount) {
balance -= withdrawAmount;
System.out.println("Withdrawal successful.");
} else {
System.out.println("Error: Insufficient balance!");
}3. else-if Ladder (Multi-Way Branching)
Evaluates multiple sequential conditions top-to-bottom. The first condition that evaluates to true executes, and the rest of the ladder is skipped:
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else {
grade = 'F'; // Default fallback
}4. Nested if (Condition within a Condition)
An if statement placed inside the body of another if statement, used when a secondary decision depends on a primary condition passing:
if (hasAccount) {
if (isAccountActive) {
System.out.println("Access granted to Banking Portal.");
} else {
System.out.println("Account is suspended. Contact support.");
}
} else {
System.out.println("Please register a new account.");
}3. Combining Multiple Conditions with Logical Operators
You can evaluate complex compound business rules within a single if expression using logical operators:
- Logical AND (&&): All individual conditions must be true.
- Logical OR (||): At least one condition must be true.
- Logical NOT (!): Reverses the condition.
// Loan Approval Criteria:
// (Age between 21 and 60) AND (Annual Income >= 5,00,000 OR CIBIL Score >= 750)
if ((age >= 21 && age <= 60) && (annualIncome >= 500000 || cibilScore >= 750)) {
System.out.println("Loan Pre-Approved!");
}Beginner Example & Code Anatomy
public class Main {
public static void main(String[] args) {
int studentMarks = 84;
boolean hasDisciplinaryAction = false;
System.out.println("=== Academic Grading & Scholarship Engine ===");
// 1. Multi-way else-if ladder for grade evaluation
char finalGrade;
if (studentMarks >= 90) {
finalGrade = 'A';
} else if (studentMarks >= 80) {
finalGrade = 'B';
} else if (studentMarks >= 70) {
finalGrade = 'C';
} else if (studentMarks >= 50) {
finalGrade = 'D';
} else {
finalGrade = 'F';
}
System.out.println("Student Marks : " + studentMarks);
System.out.println("Assigned Grade: " + finalGrade);
// 2. Nested if with compound logical validation for scholarship
if (finalGrade == 'A' || finalGrade == 'B') {
if (!hasDisciplinaryAction) {
System.out.println("Scholarship : ELIGIBLE (โน25,000 Annual Grant Approved)");
} else {
System.out.println("Scholarship : DISQUALIFIED (Disciplinary Record Found)");
}
} else {
System.out.println("Scholarship : NOT ELIGIBLE (Requires Grade B or higher)");
}
}
}
๐ Line-by-Line Code Explanation
else if (studentMarks >= 80)
Evaluates only because studentMarks < 90 was false; 84 >= 80 evaluates to true, assigning finalGrade = 'B'.
if (finalGrade == 'A' || finalGrade == 'B')
Logical OR checks if student achieved either top grade tier.
if (!hasDisciplinaryAction)
Logical NOT inverts boolean false to true, verifying clean disciplinary standing.
Practical Real-World Example
public class ATMWithdrawalSecurity {
public static void main(String[] args) {
int enteredPin = 4321;
int registeredPin = 4321;
double balance = 10000.00;
double withdrawAmt = 3500.00;
boolean isCardActive = true;
System.out.println("--- Secure ATM Transaction Processing ---");
// Step 1: Validate PIN authentication
if (enteredPin == registeredPin) {
// Step 2: Validate Card Status
if (isCardActive) {
// Step 3: Validate Sufficient Funds
if (withdrawAmt <= balance) {
balance -= withdrawAmt;
System.out.println("โ Cash Dispensed: โน" + withdrawAmt);
System.out.println("โ Remaining Balance: โน" + balance);
} else {
System.out.println("โ Transaction Failed: Insufficient funds in account!");
}
} else {
System.out.println("โ Transaction Failed: Card is blocked or inactive!");
}
} else {
System.out.println("โ Security Alert: Incorrect PIN entered!");
}
}
}
- Accidentally placing a semicolon after if: Writing "if (x > 10);" terminates the if statement immediately, causing the block underneath to ALWAYS execute regardless of the condition!
- Using single = (assignment) instead of == (comparison): Writing "if (isStudent = true)" assigns true instead of checking equality.
- Unreachable else-if conditions: Writing "if (score >= 60) ... else if (score >= 90) ..." means score >= 90 will never execute because score >= 60 catches it first. Always order conditions from most restrictive to least restrictive.
Test your understanding by writing the code directly in your editor or running in our online Java compiler:
// Coding Challenge:
// Write a program to calculate Electricity Bill based on units consumed:
// - Up to 100 units: โน3.00 per unit
// - 101 to 200 units: โน4.50 per unit
// - Above 200 units: โน6.00 per unit
// If units = 150, calculate and print the total bill amount.
public class Main {
public static void main(String[] args) {
int units = 150;
// TODO: Calculate bill using else-if ladder
}
}
๐ก Frequently Asked Questions & Interview Insights
โ Is the curly brace {} mandatory for single-line if statements?
Technically no, but it is considered an essential industry best practice to ALWAYS use curly braces {}. Omitting braces often leads to catastrophic bugs (like Apple's famous "goto fail" security vulnerability).
โ What is the performance difference between multiple if statements vs else-if ladder?
Multiple individual "if" statements evaluate EVERY condition even if earlier conditions passed. An "else-if" ladder halts evaluation the instant one condition passes, saving CPU cycles.
โ Can an if statement evaluate non-boolean values like numbers in Java?
No! Unlike C/C++ or JavaScript where 0 is false and 1 is true, Java conditions MUST strictly evaluate to a boolean type (true or false). Writing "if (1)" is a compile error.
๐ Quick Chapter Recap
- if, if-else, and else-if ladders control execution flow based on boolean expressions.
- Nested if statements allow multi-tier validation checks.
- Always order else-if conditions from highest/most specific to lowest/most general.
- Always enclose conditional code blocks inside curly braces {}.