Open In App

Nested if in Java

Generally, if condition works like yes or no type. If the condition satisfies, it executes some block of code. Otherwise, it doesn’t execute the code. Let us see the syntax of the simple if condition.

Syntax : 



if( condition ){

       statements ;
       
}

Nested if condition 

Nested means within. Nested if condition means if-within-if. Nested if condition comes under decision-making statement in Java. There could be infinite if conditions inside an if condition. The below syntax represents the Nested if condition.

Syntax : 



if( condition ){

      if( condition ){
      
                if( condition ){
                
                         ......
                }
       }
}

Note – If the inner condition satisfies then only outer if will be executed. Along with if conditions we can write else conditions also.

Example 1 




import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG
{  
    public static void main(String args[])
    {
        int a=10;
          int b=20;
       
        if(a==10){
            if(b==20){
                System.out.println("GeeksforGeeks");
            }
        }
    }
}

Output
GeeksforGeeks

Code explanation :

Example 2 :




import java.util.*;
import java.lang.*;
  
class GFG
{  
    public static void main(String args[])
    {
        int a=10;
          int b=20;
        
        if(a==10){
  
            if(b!=20){
                System.out.println("GeeksforGeeks");
            }
            
            else{
                System.out.println("GFG");
            }
        }
    }
}

Output
GFG

Code explanation :

Nested if condition comes under decision-making statement in Java. It contains several branches with an if condition inside another if condition. The syntax, code examples, and explanations of Nested-if statements are covered in detail in the above article.


Article Tags :