3 Program structure

 

This chapter covers

  • Mistakes that happen when using ifelse chains
  • Problems using while and for 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 ifelse), 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 ifelse 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:

3.2 Mistake 16: A condition dominated by a previous condition

3.3 Mistake 17: Accidental pass through in a switch statement

3.4 Mistake 18: Malformed classic for loop

3.5 Mistake 19: Not using the loop variable

3.6 Mistake 20: Wrong loop direction

3.7 Mistake 21: Loop overflow

3.8 Mistake 22: Idempotent loop body

3.9 Mistake 23: Incorrect initialization order

3.9.1 Static fields

3.9.2 Subclass fields

Summary