Nested if else in Java

Nested if else in Java

At times, we might require to nest the if and else, which means that sometimes, we are required to write if inside an if, or something like that. For example, if we are checking if someone is eligible to vote, we would check 2 things basically, like if the person is 18 or above in age, and also we are going to check whether or not the person has a voter id. If both the conditions are true, then only we are going to allow the user to vote.

So, in such situations, we are required to nest the conditional statements. Here is the program demonstration for the same thing discussed above.

public class Main{
public static void main(String[] args) {
int age = 20; // the person is 20 years old
boolean hasVoterId = false; // the person does not have a voter id
if (age >=18){ // checking if the user is 18 or above!
if (hasVoterId){ // checking if the user has voter id… may be true or false
System.out.println(“Person is eligible for voting!”);
}
else{
System.out.println(“Eligible but not having voter id”);
}
}
else{
System.out.println(“Sorry… not eligible for voting!”);
}
}
}

As you can see from the above program, we are nesting the if statements. This is like we are checking some condition, and if that condition comes out to be true, we are checking another condition inside that, and if that condition is true, we are doing something. Those if statements can also have their corresponding else statements as well. We are going to nest the conditional things, as and when required.

In the above example, from the input, we can see that the age of the person is 20, so he is above the age of 18, but he is not having a voter id, as can be seen with help of another boolean variable. So, checking both the conditions, the person is not found eligible for voting.