AP® Computer Science A · Unit 1 · Topic 1.8
Comments, Preconditions, and Postconditions
Comments explain code to people, not the compiler. Preconditions state what a method requires to work correctly, and postconditions state what it guarantees once it finishes.
The compiler deletes every comment before your program runs, so comments exist for the next human who reads the code, including future you. Java gives three forms. Two slashes mark off the rest of a line. A slash followed by a star, with a star-slash to close it, can stretch across many lines and is used for longer notes. A slash with two stars opens a Javadoc comment, placed right above a method, which documentation tools scan automatically to build reference pages, pulling out tags like at-param for each parameter and at-return for the return value.
Preconditions and postconditions are a special kind of comment: a contract. The precondition lists what must be true about the input before the method is called; the postcondition lists what will be true after it finishes, assuming the precondition held. Writing average(int[] nums) with precondition nums has at least one element, and postcondition returns the arithmetic mean of the elements, tells any caller exactly what deal they are making. A precondition is not a run-time check. Java does not pause and verify it for you; the method's code will simply do whatever its instructions say, even with bad input, which often means a crash or a meaningless answer.
This connects directly to why method signatures and parameters matter earlier in the unit: the contract is what makes a method usable without reading its internals. Later, when you write your own methods, preconditions and postconditions become the spec you design against, and postconditions in particular foreshadow reasoning about what a method returns and why it can be trusted to return it.
Key terms
- Precondition
- A condition the caller must guarantee is true before calling a method, for it to work correctly.
- Postcondition
- A condition the method guarantees is true after it finishes, provided the precondition held.
- Javadoc comment
- A comment opened with slash-star-star, scanned by tools to auto-generate documentation pages.
- Block comment
- A comment opened with slash-star and closed with star-slash, able to span multiple lines.
Watch it explained
- How it worksHow do the three comment forms in Java mark off different amounts of text?
- How it worksWalk me through how a precondition fences off the inputs a method promises to handle.
- Worked exampleFind the precondition and postcondition for a method that averages the values in an array.
- Common mistakeWhy doesn't a precondition make the method check its own inputs at run time?
Check yourself
End of topic.