Programming Java: Nesting If Statements - dummies

Programming Java: Nesting If Statements

By John Paul Mueller

Sometimes a decision in your Java application, as in real life, requires multiple levels. For example, if the ceiling is painted orange, then you may also need to decide whether the walls are painted yellow or red.

Another form of multiple level decision-making is a menu. A user may have to decide between items A, B, or C, but isn’t allowed to pick two at the same time (items A and B). Fortunately, you can create as many levels of if statements as required to handle this problem. Combining multiple levels of if statements to make complex decisions is called nesting.

Nesting makes it possible to create multiple decision-making levels within an application. You can combine all sorts of statements into a cohesive unit in order to make a decision. Nesting lets you focus on a particular part of the decision-making process and perform the process one step at a time, rather than creating a horribly complex expression.

Menus are one of the decision-making processes you’ll encounter quite often in applications. Most real world decisions aren’t just between this or that, but rather they involve shades of gray, as in “You must choose one item from a list of possible choices.”

The basic if statement could be used for every task. However, writing code using just the basic if statement can become boring and even introduce errors (bugs) into your application.

The if…else statement makes it possible to perform precisely the same task using just one structure. The if…else statement says that if the condition is true, the application should perform one set of tasks, but if the condition is false, it should perform a completely different set of tasks.

A bug is an error in the code that you write. Errors make your application behave in ways that you didn’t anticipate. Anyone using your application will get results different from the results you wanted to provide them with.

Bugs cause all sorts of problems. For example, a bug in the wrong place could cause your application to stop working or give a virus writer an opportunity to invade your application. Simplifying your code and using the appropriate statements is one way to decrease bugs.