Introduction
The Java Nested if statement is an advanced form of the if statement where one if statement is placed inside another if statement. It is used when a program needs to evaluate multiple conditions in a hierarchical manner before executing a block of code.
For example, before allowing a user to log in to an online banking application, the system may first verify whether the username is correct and then check if the password is valid.
A nested if statement makes such decision-making possible by allowing one condition to be evaluated only if another condition is already true.
What is Java Nested if Statement?
A Nested if statement in Java is an if statement placed inside another if statement. The inner if statement is executed only when the outer if condition evaluates to true.
This allows Java programs to perform multiple levels of decision-making.
How It Works
The execution follows this sequence:
- Java checks the outer if condition.
- If the outer condition is false, the inner if statement is skipped.
- If the outer condition is true, Java evaluates the inner if condition.
- If the inner condition is also true, the nested block executes.
Syntax
The syntax of a Java Nested if statement is shown below:
if (condition1) {
// Outer if block
if (condition2) {
// Inner if block
}
}
Explanation
- condition1 is evaluated first.
- If condition1 is true, Java proceeds to evaluate condition2.
- If both conditions are true, the code inside the inner if block is executed.
- If either condition is false, the corresponding block is skipped.
Flow of Java Nested if Statement
The execution flow can be understood as follows:
Check Condition 1
|
False -----------------> Skip Inner if
|
True
|
Check Condition 2
|
False -----------> Skip Block
|
True
|
Execute Statements
The second condition is evaluated only after the first condition becomes true.
Example 1: Student Eligibility
public class Main {
public static void main(String[] args)
int marks = 82;
int attendance = 90;
if (marks >= 40)
if (attendance >= 75) {
System.out.println("Eligible for Final Examination");
}
}
}
}
Output
Explanation
- The student has passed the minimum marks requirement.
- The attendance is also above 75%.
- Therefore, the student is eligible.
Example 2: Employee Bonus
public class Main {
public static void main(String[] args) {
int experience = 6;
doble rating = 4.5;
if (experience >= 5) {
if (rating >= 4.0)
System.out.println("Bonus Approved");
}
}
}
}
Output
The employee receives the bonus only when both conditions are satisfied.
Example 3: ATM Withdrawal
public class Main {
public static void main(String[] args) {
boolean cardValid = true;
int balance = 12000;
int withdraw = 5000;
if (cardValid) {
if (balance >= withdraw) {
System.out.println("Transaction Successful");
}
}
}
}
Output
The system first verifies the ATM card and then checks whether sufficient balance is available.
Example 4: Online Shopping
boolean premiumMember = true;
double purchase = 6500;
if (premiumMember)
if (purchase >= 5000) {
System.out.println("Special Discount Applied");
}
}
Output
Only premium customers with eligible purchases receive the discount.
Example 5: Login Authentication
String username = "admin";
String password = "Java123";
if (username.equals("admin"))
if (password.equals("Java123")) {
System.out.println("Login Successful");
}
}
Output
The password is verified only after the username is validated.
Real-life Examples
1. College Admission
A university may first check whether the student passed the entrance exam. If yes, it then verifies the required percentage before confirming admission.
int entranceScore = 85;
int percentage = 78;
if (entranceScore >= 70)
if (percentage >= 75) {
System.out.println("Admission Confirmed")
}
}
2. Loan Approval
Banks usually perform multiple checks before approving a loan.
int salary = 70000;
int creditScore = 780;
if (salary >= 50000) {
if (creditScore >= 750) {
System.out.println("Loan Approved")
}
}
3. Company Access System
boolean employee = true;
boolean idCard = true;
if (employee) {
if (idCard)
System.out.println("Access Granted");
}
}
4. Movie Ticket Booking
int age = 22;
boolean ticketAvailable = true;
if (age >= 18) {
if (ticketAvailable) {
System.out.println("Booking Successful");
}
}
5. Online Examination
boolean registered = true;
boolean feePaid = true;
if (registered) {
if (feePaid) {
System.out.println("Exam Access Allowed");
}
}
Advantages of Java Nested if Statement
- Allows multiple conditions to be checked step by step.
- Makes complex decision-making easier.
- Helps implement hierarchical business rules.
- Reduces unnecessary condition checking.
- Widely used in authentication, banking, and enterprise applications.
- Improves code organization when conditions depend on one another.
When Should You Use Nested if?
Use a nested if statement when:
- One condition depends on another.
- You need multiple levels of validation.
- The second condition should be checked only if the first condition is true.
- You are implementing layered business logic.
For independent conditions, using logical operators (&& or ||) may be a simpler alternative.
Nested if vs Logical AND (&&)
Consider the following nested if statement:
if (age >= 18) {
if (citizen) {
System.out.println("Eligible to Vote");
}
}
The same logic can often be written using the logical AND operator:
if (age >= 18 && citizen) {
System.out.println("Eligible to Vote");
}
Which One Should You Use?
- Use Nested if when the second condition depends on the first or when additional processing is needed between conditions.
- Use && for simple combined conditions to keep the code concise.
Common Mistakes
1. Forgetting Curly Braces
Incorrect:
if (marks >= 40)
if (attendance >= 75)
System.out.println("Eligible");
Although this compiles, using braces improves readability and avoids errors.
Correct:
if (marks >= 40) {
if (attendance >= 75) {
System.out.println("Eligible");
}
}
2. Writing Unnecessary Nested if Statements
Incorrect:
if (age >= 18) {
if (citizen) {
System.out.println("Eligible");
}
}
A simpler version is:
if (age >= 18 && citizen) {
System.out.println("Eligible");
}
3. Comparing Strings with ==
Incorrect:
if (username == "admin") {
Correct:
if (username.equals("admin")) {
4. Using Non-Boolean Conditions
Incorrect:
int age = 20;
if (age) {
}
Correct:
if (age > 18) {
}
5. Deeply Nested Code
Avoid creating many levels of nested if statements because they make code difficult to read and maintain.
Instead of:
if (...) {
if (...) {
if (...) {
if (...) {
}
}
}
}
Consider restructuring the logic using methods, logical operators, or early returns where appropriate.
Best Practices
- Keep nesting levels as low as possible.
- Use meaningful variable names.
- Add comments for complex business logic.
- Use braces even for single statements.
- Replace unnecessary nesting with logical operators when possible.
- Test every possible execution path.
Conclusion
The Java Nested if statement is a powerful decision-making construct that allows you to evaluate multiple dependent conditions in a structured manner. It is particularly useful when one condition must be satisfied before checking another, making it ideal for real-world applications such as login systems, banking software, loan approval processes, online shopping, and access control.
In this guide, you learned what a Java Nested if statement is, how it works, its syntax, execution flow, practical examples, real-life applications, advantages, best practices, common mistakes, and frequently asked interview questions.