Nested if in Java refers to having one if statement inside another if statement. If the outer condition is true the inner conditions are checked and executed accordingly. Nested if condition comes under decision-making statement in Java, enabling multiple branches of execution.
Note:
- Normal if condition checks condition independently which means each condition works on its own.
- Whereas nested if checks conditions that depend on each other, which means one condition is only checked if another condition is true.
Example 1: The below Java program demonstrates the use of nested if statements to check multiple conditions and execute a block of code when both conditions are true.
Java // Java program to demonstrate the // use of nested if statements import java.io.*; import java.lang.*; import java.util.*; class Geeks { public static void main(String args[]) { int a = 10; int b = 20; // Outer if condition if (a == 10) { // Inner if condition if (b == 20) { System.out.println("GeeksforGeeks"); } } } } Explaination: In the above example, one if condition is placed inside another. If both conditions are true, it prints GeeksforGeeks
Syntax of Nested if
if (condition1) {
if (condition2) {
if (condition3) {
// statements;
}
}
}
Note: If the outer condition satisfies then only the inner condition will be checked. Along with if condition, else condition can also be executed.
Example 2: The below Java program demonstrates the use of nested if-else statements to execute multiple conditions and different code block based on weather the inner condition is true or false.
Java // Java Program to demonstrate the use of // nested if-else statements import java.lang.*; import java.util.*; class Geeks { public static void main(String args[]) { int a = 10; int b = 20; // Outer if condition if (a == 10) { // Inner if condition if (b != 20) { System.out.println("GeeksforGeeks"); } else { System.out.println("GFG"); } } } } Explanation: In the above example, it first checks if a is equal to 10. If the condition satisfies, it then checks the inner condition b != 20. If the inner condition is false, the else block executes, it prints GFG.
Advantages
- It provides a clear structure for handling multiple related conditions.
- It ensures that inner conditions are evaluated only when necessary, improving efficiency.
Disadvantages
- Overuse of this condition can make the code harder to read and maintain.
- It may lead to increased complexity if not structured properly.
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java
My Profile