Java nesting if statements

Nested if-else statement in Java (with examples)

When faced with a choice, we always ask ourselves a series of questions before determining the best course of action in light of the circumstances. In programming languages, we implement this very case with the use of if-else statements. But, in some cases, one condition is not enough to get the desired answer. In such cases, we implement if else statements one inside another, this is known as nested if else. In this article, we’ll learn how to implement nested if-else statement in java.

If else

Before moving to nested if-else statements. Let’s revise what if else statements are. An if-else statement is a conditional statement that decides the execution path based on whether the condition is true or false. In other words, an if-else statement is used to carry out a particular task (job) based on whether or not a defined condition is true.

if ( condition ) < statement1; // For true case. > else < statement2; // For false case. >
Code language: Java (java)

Each case in this example contains either a single statement or many statements enclosed in curly braces indicating an action to be performed. Any boolean expression that produces a boolean value qualifies as the condition.

Читайте также:  Java return character in string

The else clause is optional, i.e it’s not necessary, we can omit the else clause. This convention can be used in all Java control statements. Let’s take a look at some examples.

Example 1: Check whether the number is divisible by 5.

public class codedamn < public static void main(String[] args) < int a=10; if(a%5==0) < //Divisible by 5 System.out.println("Divisibe by 5"); > else < //Not divisible by 5 System.out.println("Not dividible by 5"); > > >
Code language: Java (java)

In the above example, if the if-condition is satisfied, the statement inside it is executed otherwise it moves to the else part. The number a=10 is divisible by 5, so it prints “Divisible by 5” and the else statement is skipped.

Nested if else statements

We saw how helpful if and else statements are, but what if we need to check for more conditions even when one condition is satisfied? In such cases, we use nested if-else statement. Nesting is the practice of enclosing several if-else statements within an if-and-else statement.

Example: Check number divisibility

Let’s take the example of odd and even. If a number is even, we also need to check whether the number is divisible by 6. And if the number is odd, we need to check whether the number is divisible by 3. Here, a single if-else statement won’t be able to solve the problem. Therefore, we need to use nested if-else statements.

public class code< public static void main(String[] args) < int n=24; //if else condition to check whether the number is even or odd if (n % 2 == 0)< //the number is even System.out.print("Even "); //nested if else condition to check if n is divisible by 6 or not if (n % 6 == 0) < //the number is divisible by 6 System.out.println("and divisible by 6"); > else < //the number is not divisible by 6 System.out.println("and not divisible by 6"); > > else < //the number is odd System.out.println("Odd "); //nested if else condition to check if n is divisible by 3 or not if(n % 3 == 0) < //the number is divisible by 3 System.out.println("and divisible by 3"); > else < //the number is not divisible by 3 System.out.println("and not divisible by 3"); > > > >
Code language: Java (java)

First, we’ll use an if statement to determine whether the number is even or odd. Then, if the number were even, we would need to put another if and else statement. In the if block we again check whether the number is divisible by 6 or not. Likewise, in the else block, we would need to determine if the number is divisible by 3 or not.

Example: Find the tallest student among 3 students

public class code < public static void main(String[] args) < int n1 = 150, n2 = 180, n3 = 170; if (n1 >= n2) < if (n1 >= n3) System.out.println("Student with height: " + n1 + " is the tallest."); else System.out.println("Student with height: " + n3 + " is the tallest."); > else < if (n2 >= n3) System.out.println("Student with height: " + n2 + " is the tallest."); else System.out.println("Student with height: " + n3 + " is the tallest."); > System.out.println("\n"); > >
Code language: Java (java)

In the above program, instead of checking for two conditions in a single if statement, we use nested if to find the tallest student’s height. We use the following conditions:

if: n1 is greater or equal to n3, n1 is the greatest.

if: n2 is greater or equal to both n3, n2 is the greatest.

Example: Check if three numbers are equal or not

public class code < public static void main(String[] args) < int a = 2; int b = 2; int c = 2; if (a == b) < // nested if else condition to check if c is equal to a and b if (a == c) < // all are equal System.out.println("Equal"); > else < // a!=c System.out.println("Not equal"); > > else < // a!=b System.out.println("Not equal"); > > >
Code language: Java (java)

Here a, b, and c have a value equal to 2. If the condition (a==b) is satisfied, it moves to the next if statement and checks if (a==c). Since this condition is satisfied in the above case it prints “Equal”.

Conclusion

In conclusion, we can say if-else statements for decision-making. They are one of the core programming concepts that you learn when you start programming. Sometimes, we need to check more than one condition, there we implement nested if-else statements. In this article, we went through some examples using nested if-else statements in Java. Additionally, you can start learning Java from scratch in the Codedamn platform by clicking here.

Sharing is caring

Did you like what Fidal Mathew wrote? Thank them for their work by sharing it on social media.

Источник

What is Nested if Statement in Java?

Java Course - Mastering the Fundamentals

Nested if refers to an if statement within an if statement. When we write an inner if condition within an outer if condition, then it is referred to as a nested if statement in java.

Nested if is a decision-making statement that works similar to other decision-making statements such as if, else, if..else, etc. It executes a block of code if the condition written within the if statement is true. However, in the nested-if statement, the block of code is placed inside another if block. And the inner block of code will execute only when the outer condition holds true.

Therefore, we use the nested if statement to evaluate more than one condition in a program and return multiple values depending on the test condition.

An example of a nested if statement could be a person should be qualified as well as an adult to be hired in a company. Therefore, in this example, first, the condition for the person’s qualification is checked, and if it is true, then only the company checks if the person is an adult or not. So, there are two conditions checked, one within another. Therefore they are nested if statements.

Syntax of Nested If Statement

The syntax for the nested if statement is as follows —

As you can see in the syntax, the inner if statement is only checked if the outer if condition is satisfied; otherwise not.

Nested If Condition

As discussed earlier, nesting refers to within. Nested if refers to if within an if statement. However, there can be any number of if statements within another if statement. The nested if statement comes under the category of the decision-making statements in Java.

Let us see the syntax for the infinite number of if statements, one within another.

However, if the outer if condition is satisfied and returns true, then only the inner if condition is checked; otherwise not. Moreover, you can also write an if..else statement within an if condition, which would be referred to as a nested if..else statement in Java.

Flowchart

Let us now understand the nested if with the help of a flowchart.

The flowchart has been created based on the below syntax

The figure below depicts how the control in a nested if condition will flow when executed.

example of nested if syntax

Working

The nested if statement works similar to an if..else statement. The only difference is that instead of an else statement, there would be another if statement in the syntax.

We will now see a code based on which the working of the nested if statement is explained further.

Let us understand how this nested if condition works when it is executed.

  • If the test_condition1, that is, a == 97 is true, then go the test_condition2, which is z == 122 .
  • If the test_condition2 is true, then execute the block of statement written inside the second if statement, which will print «Correct» as the output.
  • However, if the test_condition2 is false, then the else part is executed if present in the program, otherwise, it will exit the loop. Here, in the above code, it is present, therefore, «Wrong» will be printed as the output.
  • If the test_condition1 is false, then the corresponding outer else part is executed, if present, otherwise it will also exit the loop.

Examples

Implement Nested-If Condition With Only If Conditions

Now we will see an example where the nested if conditions are implemented only using the if condition.

In this example, we are given two numbers, x and y . These nummbers are to be checked if they are equal with 30 and 40 respectively based on which certain statement is printed.

Let us see the code for the same.

As you can see in the above code, first, the condition x == 30 is checked, and if satisfied, checks for the next condition y == 50 , which when satisfied, prints the subsequent statements in the if block.

Nested-If Condition With Both If and Else Conditions

Now let us see the nested if condition using both the if and else conditions in a program.

In this example as well, we are given two numbers, x and y . These numbers are to be checked if they are equal with 30 and 40 respectively based on which certain statement is printed. However, the difference lies with the introduction of an else block in the program.

Let us see the code for the same.

As you can see in the above code, first, the condition x== 30 is checked. If this condition is true, then only the nested if..else condition is checked further. However, if the first condition is true then the next if condition y == 40 is checked. If it is true, then the if block is executed; otherwise, the statements of the else block are executed.

The Nested-If Condition That Takes Input From the User

Now let us see the nested if conditions that take the input from the user.

In this example, we will find the right vaccine to be injected into a particular person. The conditions for getting a vaccine are that a person must be above 18 years of age, after which different genders will be provided with different kinds of vaccines in the market.

In our problem, we will be taking the age and the gender of a person as the input from the user.

Let us see the code for the same.

The output «CovidShield» came when the gender and age variables are provided with the input ‘M’ and 30 .

Therefore, as you can see in the above code, first of all, the inputs are taken from the user, after which if the person is above 18 years old then only they are provided with a different type of vaccine according to their gender.

First of all, if the gender is ‘M’, that is, a male, then they are provided with «CovidShield vaccine». However, if the gender is ‘F’, that is, female, they are injected with «Covaxine» whereas the rest all the genders have been provided with the «Sputnik» dose.

Conclusion

  • Nested if statement is a decision-making statement that is used when we have to make decisions based on certain conditions.
  • The nested if statement in Java is a set of if conditions one within another.
  • The inner if conditions are only executed when the outer if condition results in true ; otherwise the corresponding else block is executed.
  • The nested if condition can also be used with nested if..else statement.

Источник

Оцените статью