ACSA Exam Prep
Unit 1 · Using Objects and Methods · Topic 1.8

Documentation with Comments

Skill 4.B

Big idea: Comments explain code to people. Preconditions and postconditions are a contract: what must be true before a method runs, and what it promises afterward.

Learning objectives
  • Describe the functionality and use of code through comments.

Three comment styles

The compiler ignores comments. Use them to explain intent, not to restate the code.

Code
// single-line comment
/* block comment
   that spans lines */
/** Javadoc comment: used to generate API documentation */
System.out.println("comments are ignored");
Output
comments are ignored

Preconditions and postconditions

A precondition is a condition that must be true just before a method runs. The method doesn't have to check it; if a caller breaks it, the method's behavior isn't guaranteed.

A postcondition is what will be true after the method finishes: what it returns, or how the object's state has changed.

/**
 * Returns the average of the values in nums.
 * Precondition: nums.length > 0
 * Postcondition: nums is unchanged
 */
public static double average(int[] nums)
{ /* implementation not shown */ }
Key points
  • // single line, /* */ block, /** */ Javadoc.
  • A precondition must be true before a method runs; the method is not expected to check it.
  • A postcondition describes the result or the new state after the method runs.
Watch out
  • On FRQs, you can assume preconditions hold. Don't waste time writing checks for them.
Exam tip
  • "Which precondition is needed" questions: find the input that would make the code crash or give a wrong answer, then pick the condition that rules it out.
Quick check
A method returns arr[0] / arr.length. Name a sensible precondition.
Show answer
arr.length > 0 (otherwise arr[0] throws an exception and the division by length would also fail).