- Nested if statements in Java allow for more complex decision-making by placing one if statement inside another. This creates a hierarchical structure where the inner if condition is only evaluated if the outer if condition is true.
SYNTAX
if (condition1) {
// Code to execute if condition1 is true
if (condition2) {
// Code to execute if condition1 AND condition2 are true
}
else {
// Code to execute if condition1 is true and condition2 is false
}
}
else {
// Code to execute if condition1 is false
}
Key Points:
- Nested if statements can be nested multiple times, allowing for complex decision trees.
- Each else statement is associated with the closest preceding if statement within the same block.
- Indentation is crucial for readability and understanding the structure of nested if statements.
- Carefully consider the logic and conditions to avoid unintended behavior.
SAMPLE PROGRAM
public class NestedIfWithoutScanner {
public static void main(String[] args) {
int num = 75; // Directly assigned value
// First condition
if (num > 0) {
System.out.println("The number is positive.");
// Second (nested) condition
if (num % 2 == 0) {
System.out.println("The number is even.");
// Third (nested) condition
if (num > 100) {
System.out.println("The number is greater than 100.");
} else {
System.out.println("The number is 100 or less.");
}
} else {
System.out.println("The number is odd.");
}
} else {
System.out.println("The number is not positive.");
}
}
}
Output
The number is positive.
The number is odd.
REFFERED LINKS
Top comments (0)