3 Program structure
This chapter covers
- Mistakes that happen when using
if
–else
chains - Problems using
while
andfor
loops - How to avoid pitfalls around the initialization of fields and classes
- Missing a call to a superclass method
- What happens if you accidentally declare a static field instead of an instance one
Java provides a number of constructions to alter the program control flow. These include branching statements (switch
and if
–else
), loop statements (for
and while
), and so on. It is common for beginners to make mistakes in control flow statements, and it is a useful skill to be able to identify them. Such mistakes may result in visiting the wrong branch, having more loop iterations than expected, and other undesirable outcomes. Another class of mistakes discussed in this chapter originates from the errors in program structure outside of the method body, like incorrect initialization order or accidental use of the static
modifier where it should not be used.
3.1 Mistake 15: A malformed if–else chain
A common and useful pattern in Java programming is an if
–else
chain that allows you to perform different actions depending on multiple conditions, like this:
if (condition1) { … } else if (condition2) { … } else if (condition3) { … } else if (condition4) { … } else { … }
When this chain is quite long, occasionally, an intermediate else
keyword will be missing: