Java Selection Statements: Nested if Statements
There will be occasions when you will want your program to execute a code block after you have tested a number of tiered conditions. The General syntax is:
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition1 and condition2 are true
}
}
For example, you might have a program that displays a statement when a condition is true as long another more general condition is also true. The following program will display “Distinction” if a students score was greater than 80%.
Let’s write the code so that the program only checks if the student score was greater than 80% if they actually achieved a passing grade in the first place – this can be achieved by nesting the if statement required to determine a Distinction grade within the if statement that determines if the student passed or not:
int passGrade = 50; int studentGrade = 80; if(studentGrade >= passGrade) { if(studentGrade >= 80) { System.out.println("Distinction"); } }
The output for this student would be “Distinction as their grade was 80%.
run: Distinction BUILD SUCCESSFUL (total time: 1 second)
As you can see, nested if statements can be very useful when you have tiers of conditions that that must all be evaluated before a code bock is executed. Had the student scored less than 80% the program would not need to run the nested if statement and there would be no output. However, it would be useful that have an output that indicated what grade the student did get int he case of scores lower than 80%. We could do this with the addition of and else.