Search⌘ K

Nested if Statements

Explore how to implement nested if statements in Java to manage complex multiway decisions. Understand why braces improve readability, how else clauses associate with if statements, and the use of else-if for clear code structure. This lesson helps you write clearer and more effective decision-making Java code.

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 ...