How to Write a Nested if...else Statement

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

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

  1. Open your text editor and create a new file that will contain the demonstration program. Type in the following Java statements.
    Java Source for Writing nested if else Statements
    The if statement tests if the make is "Ford". The nested if...else statement will determine if the Ford is a Model T or another model manufactured by Ford.

  2. Save your file as

  3. Open a command prompt and navigate to the folder containing your Java program. Type in the command to compile your program and hit Enter.
    Compile Source for Writing nested if else Statements

  4. Run the Java runtime launcher to run your program. Notice in the output that the nested if...else correctly determined that the Ford was a Model T and therefore is a classic car.
    Run Writing nested if else statements
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.