Open In App

Nested if in Java

Improve
Improve
Like Article
Like
Save
Share
Report

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 

Java




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 :

  • In the first step, we have imported the required packages.
  • In the next step, we have created a class names GFG
  • In the next step, we have written the main method.
  • Within the main method, we have assigned values to variables.
  • Using nested if conditions, we have printed a statement.
  • Here two statements are true. Hence statement was executed successfully.

Example 2 :

Java




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 :

  • In the first step, we have imported the required packages.
  • In the next step, we have created a class names GFG
  • In the next step, we have written the main method.
  • Within the main method, we have assigned values to variables.
  • Using nested if conditions, we have printed a statement.
  • Here inner if the condition is not true. Hence else part is executed.

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.



Last Updated : 07 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads