Nested if Statement
A nested if statement is an if statement inside another if or else block. It is used when one condition depends on another condition and decisions must be made in a hierarchical or step-by-step manner. This concept is important for business rules, validations, and interviews.
What Is a Nested if Statement?
- An if inside another if or else
- Inner condition is evaluated only if the outer condition is true
- Used for dependent conditions
Basic Syntax
if (condition1) {
if (condition2) {
// code if both conditions are true
}
}
Simple Example
int age = 20;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("Eligible to drive");
}
}
Why it matters: hasLicense is checked only if age condition passes.
Nested if with else
int marks = 75;
if (marks >= 40) {
if (marks >= 90) {
System.out.println("Grade A");
} else {
System.out.println("Grade B");
}
} else {
System.out.println("Fail");
}
Real-Time Example (Business Logic)
if (isUserLoggedIn) {
if (hasPremiumAccess) {
showPremiumContent();
} else {
showBasicContent();
}
}
Nested if vs Logical Operators
Nested if
if (age >= 18) {
if (hasId) {
allowEntry();
}
}
Using Logical Operator (&&)
if (age >= 18 && hasId) {
allowEntry();
}
Best Practice: Use logical operators when conditions are independent.
else Binding Rule (Important Interview Trap)
In nested if, else always binds to the nearest unmatched if.
if (a > b)
if (a > c)
System.out.println("A is largest");
else
System.out.println("C is largest");
Best Practice: Always use braces {}.
When to Use Nested if
- Conditions are dependent
- Step-by-step validation
- Multi-level business rules
When to Avoid Nested if
- Deep nesting reduces readability
-
Can often be replaced with:
- Logical operators
- else-if ladder
- switch statement
Common Beginner Mistakes
- Missing braces
- Excessive nesting
- Confusing else binding
- Using nested if for independent conditions
Interview-Ready Answers
Short Answer
A nested if statement is an if inside another if or else block, used for dependent conditions.
Detailed Answer
In Java, nested if statements allow checking multiple conditions in a hierarchical manner. The inner if is evaluated only when the outer condition is true, making it suitable for step-by-step decision-making.
Key Takeaway
Nested if statements are powerful for dependent logic, but should be used carefully to maintain readability and avoid logical confusion.