When an if statement is present inside another if statement, called nested if statement.
//For example, if(n%2==0) { if(n<40) { System.out.println("have got an even number<40"); } } else System.out.println("have got an odd number");
Now the message for an even value is displayed only if the value of number is also less than 40. There are three possible outcomes from this code fragment. If number is even and less than 40, you will see the message to that effect, if number is even and is not less than 40, there will be no output, and finally if number is odd, a message will be displayed.
If-else-if Ladder: It is based upon a sequence of nested ifs. The general form of the if-else-if ladder is :
if(condition) statement ; else if(condition) statement ; else if(condition) statement ; ----- ----- else statement ;
The if statements are executed from the top down. Once one of the condition is true, the statement associated with that if is executed, and rest of the ladder is neglected. If none of the conditions is true, then the final else statement will be executed.
If there is no final else and all other conditions are false, then no action will take place.
Let's see a program to demonstrate if-else-if ladder:
import java.util.Scanner; class NestedIfDemo { public static void main(String[] args) { int m1,m2,m3,m4; double avg; Scanner s=new Scanner(System.in); System.out.println("enter the marks"); m1=s.nextInt(); m2=s.nextInt(); m3=s.nextInt(); m4=s.nextInt(); avg=(m1+m2+m3+m4)/4; if(avg>60) System.out.println("1st division"); else if((avg>=40)&&(avg<60)) System.out.println("2nd division"); else if((avg>=30)&&(avg<40)) System.out.println("3rd division"); else System.out.println("fail"); } }
enter the marks
62
35
45
52
2nd division
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc