Java Conditional Statement: Nested If-Else Statements

Nested If/Else Statement 

To understand what a Nested If / Else Statement is , let us first study what does the term Conditional Statement imply.

Conditional Statements  are a feature of programming languages that are used to make decisions based on the conditions. Conditional statements execute sequentially when there is no condition around the statements. If we apply some condition for a set of statements within the scope, the execution flow may change based on the result evaluated by the condition. This process is called decision making.

The ‘Nested If/Else- Statement ‘ is an example of such conditional statements.

Understanding the concept

Nested If in programing language can be assumed as placing an If Statement within another IF Statement. Nested If/Else is helpful when we want to check a certain condition inside a condition. If Else Statement prints varying statements based on the expression result which are boolean values : true or false. 

Let us have a look on how the control flows through such a functionality:

  • Control flow verifies the first given condition.
  • If condition 1 is false, then Statement 3, is executed. 
  • If condition 1 is true, then the control flow further verifies the Condition 2.
  • Now if condition 2 is false, Statement 2 is executed.
  • But if condition 2 is true, Statement 1 is executed.

For better understanding, the working of this flowchart has been given in the following image.

Nested If Statements

Syntax of If- Else Statement

if(condition 1)
{
    if(condition 2)
    {
        statement 1;
    }
    else 
    {
        statement 2;
    }
}
else
{
    statement 3;
}

Now that we have seen the syntax of the nested if- else statement, let us understand it further with the help of an example.

Run
public class Main
{
	public static void main(String[] args) {
		 int a= 100;
		 if(a<250)
		 {
		     if(a<150)
		     System.out.println("Hey Prepster, Happy Learning");
                     else
		     System.out.println("Keep going, keep learning");
		 }

		 else
		 System.out.println("Welcome to Prepinsta");

	}
}

Output: 

Hey Prepster, Happy Learning

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription