How to Write a Nested if...else Statement
if statement in Java is the primary decision-making construct. The
if statement tests a condition that, if true, causes the statements within the scope of the
if to execute. An
if statement supports an optional
else clause. If the condition evaluates to false, then the statements in the
else clause are executed.
if...else statements are embedded within an outer
if and permit the developer to test additional conditions. To learn how to write nested
if...else statements, follow these four steps.
- Open your text editor and create a new file that will contain the demonstration program. Type in the following Java statements.
ifstatement tests if the make is "Ford". The nested
if...elsestatement will determine if the Ford is a Model T or another model manufactured by Ford.
- Save your file as WriteANestedifelseStatement.java.
- Open a command prompt and navigate to the folder containing your Java program. Type in the command to compile your program and hit Enter.
- Run the Java runtime launcher to run your program. Notice in the output that the nested
if...elsecorrectly determined that the Ford was a Model T and therefore is a classic car.