Last Updated : 23 Jul, 2025
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:
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 ifif (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 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.
AdvantagesRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4