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.
if runs only when outer condition is trueGeneral structure of a nested if–else:
// 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
}
// 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");
}
}
}
Grade: Distinction
Since marks are 78:
marks >= 40) is truemarks >= 75) is also true
else if when conditions are sequential