← Back to Chapters

Nested if–else in Java

? Nested if–else in Java

? Quick Overview

A nested if–else statement in Java means placing one if or if–else inside another. It is used when decisions depend on multiple related conditions.

? Key Concepts

  • Used for multi-level decision making
  • Inner if runs only when outer condition is true
  • Helps evaluate dependent conditions
  • Common in grading, authentication, and validation logic

? Syntax / Theory

General structure of a nested if–else:

? View Code Example
// General syntax of nested if-else
if(condition1){
if(condition2){
// Code when both conditions are true
}else{
// Code when condition1 is true and condition2 is false
}
}else{
// Code when condition1 is false
}

? Code Example

? View Code Example
// Java program to check grade using nested if-else
class NestedIfExample{
public static void main(String[] args){
int marks = 78;

if(marks >= 40){
if(marks >= 75){
System.out.println("Grade: Distinction");
}else{
System.out.println("Grade: Pass");
}
}else{
System.out.println("Grade: Fail");
}
}
}

? Live Output / Explanation

Output

Grade: Distinction

Since marks are 78:

  • First condition (marks >= 40) is true
  • Second condition (marks >= 75) is also true
  • So, Distinction is printed

 

✅ Tips & Best Practices

  • Keep nesting levels minimal for readability
  • Use proper indentation to avoid confusion
  • Consider else if when conditions are sequential
  • Add meaningful comments for clarity

? Try It Yourself

  • Modify the program to calculate grades A, B, C, D
  • Create a login validation using nested if–else
  • Check if a number is positive, negative, or zero