Nested if Statements
In this lesson, we will look at nesting if statements that allow for our program to choose from among several possible actions.
We'll cover the following
What is a nested if
statement?
Previously, we saw the syntax of an if
statement as follows:
if ( condition )
statement1
else
statement2
Both statement1 and statement2 represent other Java statements, including if
statements and compound statements. Recall that a compound statement consists of one or more Java statements enclosed in a pair of braces. The statements within these braces can also be other if
statements.
When an if
statement occurs within another if
statement, we say that they are nested. Any of these statements can have an else
clause.
Example
Suppose that we have two objects that represent two people. Each object has the method getAge
that returns the age of a person as an integer. You wonder which person is older. The following
program will tell you:
Get hands-on with 1400+ tech skills courses.