---
title: "Documentation with Comments | FiveStudy"
description: "The three Java comment forms, and the two promises a method makes — precondition and postcondition — that decide who is at fault when it misbehaves. AP CS A learning objective 1.8.A."
url: https://fivestudy.com/guides/documentation-with-comments
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# Documentation with Comments

[Figure: FiveStudy logo]

FiveStudy

Unit 1 · Topic 1.8

Unit 1 · Using Objects and Methods · Topic 1.8

# Documentation *with Comments*

Three comment forms, and the two promises — precondition and postcondition — that decide who is to blame when a method misbehaves.

Exam-day recap

- **1.8.A** covers both halves: functionality is what the code does; use is what a caller must guarantee and gets back.
- Three comment forms: `//` single-line, `/* */` block across lines, `/** */` Javadoc that generates API documentation.
- All three comment forms are ignored by the compiler and never executed; a comment can be completely wrong and the program still runs.
- A **precondition** is a condition that must be true just prior to the execution of a method for it to behave as expected.
- There is no expectation that a method will check its preconditions; a broken precondition is the caller's fault.
- A **postcondition** must always be true after execution, describing the return value or the object's attributes.
- A stated precondition means do not write the check; if `nums.length > 0` is guaranteed, checking for empty is not rewarded.
- A contract is only as strong as the conditions it names; stated conditions can still leave a failing case, like `int[1][0]`.
- A stale comment is more dangerous than no comment because the compiler never checks it, so it stays wrong while looking authoritative.

## 1A Method With an Invisible Contract

```
public static int middleValue(int[] data)
{
   return data[data.length / 2];
}
```

Three lines, no comments, and already two unanswered questions. What happens on an empty array? What does "middle" mean when the length is even — the lower of the two, or the upper?

The code answers the second question (it takes the upper) and crashes on the first. Neither answer is written down anywhere, so every caller has to read the body to find out. That is the problem this topic solves.

Both questions have answers. Neither is written anywhere except in memory, at run time:

The learning objective

**1.8.A — describe the functionality and use of code through comments.** Two halves, and students usually only learn the first. *Functionality* is what the code does. *Use* is what a caller must guarantee and what they get back — the precondition and postcondition. The second half is where the exam points are.

## 2Three Kinds of Comment

| Form | Name | What it is for |
| --- | --- | --- |
| `//` | Single-line comment | A note from here to the end of the line |
| `/* */` | Block comment | A note spanning as many lines as you like |
| `/** */` | Javadoc comment | A block comment that also generates API documentation |

```
// a single-line comment runs to the end of this line

/* a block comment
   can run across
   several lines */

/** a Javadoc comment looks like a block comment
 *  with an extra star, and its contents become
 *  part of the generated API documentation */
```

The property all three share

Comments are **ignored by the compiler** and are **not executed** when the program runs. They exist for the original programmer and for anyone else reading the code — never for the machine. A comment can therefore be completely wrong and the program still runs exactly as before, which is precisely why a stale comment is dangerous.

The distinction that gets tested

`/* */` and `/** */` behave identically *at runtime* — both are skipped. The difference is entirely in tooling: the Javadoc form is the one collected into **API documentation**. If a question asks which comment type documents a class for other programmers to use, the answer is `/** */`.

### 2.1 Comment the Why, Not the What

A comment that restates the code earns nothing and rots quickly:

```
count++;   // add one to count
```

A comment that supplies what the code cannot say earns its place:

```
count++;   // header row is counted separately, so start the body at 1
```

The first repeats a line anyone can read. The second records a decision that is invisible in the syntax — and if it later turns out to be wrong, the comment is where the argument happens.

## 3Preconditions — What the Caller Must Guarantee

Definition

A **precondition** is a condition that must be true **just prior to the execution of a method** in order for it to behave as expected.

Written for `middleValue`, the missing promise becomes explicit:

```
/** Returns the value at the middle index of data.
 *  Precondition: data.length > 0
 */
public static int middleValue(int[] data)
```

The clause students miss

The course states it directly: **there is no expectation that the method will check to ensure preconditions are satisfied.** A precondition is not a guard, and it is not validation. It is a stated assumption — and if the caller breaks it, the method is entitled to do anything at all, including crash.

### 3.1 Who Is at Fault

This is the whole reason preconditions exist, and it is worth stating as a rule:

| Situation | Whose fault |
| --- | --- |
| Precondition met, method returns the wrong answer | **The method.** It failed its own promise |
| Precondition broken, anything at all happens | **The caller.** The method never promised behavior here |
| No precondition stated, method crashes on empty input | **Ambiguous** — which is exactly why you state it |

"It should check anyway" is a different design decision

A method *may* validate its input, and sometimes should. But once it does, that behavior belongs in the postcondition — "returns −1 if the array is empty" is a promise about what happens, not a precondition. Do not write a precondition and then check it and call that documentation; decide which of the two you are offering.

### 3.2 Writing Them Well

| Weak | Strong | Why |
| --- | --- | --- |
| "data is valid" | `data.length > 0` | Checkable. "Valid" means nothing without a definition |
| "the list is sorted" | "the list is sorted in increasing order" | Direction matters and was left ambiguous |
| "n is a number" | `0 <= n < scores.length` | The type is already in the signature; the range is not |
| "call this first" | "the account has been opened" | States the condition, not the ritual |

A test for a good precondition

Could a caller **check it** before calling? `data.length > 0` passes — anyone can test it. "data is reasonable" fails, because no caller can determine whether they have satisfied it.

## 4Postconditions — What the Method Guarantees

Definition

A **postcondition** is a condition that must **always** be true after the execution of a method. Postconditions describe the outcome in terms of **what is being returned** or **the current value of the attributes of an object**.

The definition names the only two things a method can actually change from the caller's point of view:

| Kind | Describes | Example |
| --- | --- | --- |
| Return value | What comes back | "returns the number of scores above the average" |
| Object state | What changed inside the object | "the balance has been reduced by amount" |

A method that returns nothing and changes nothing has no postcondition worth writing — which is a good sign it does nothing.

### 4.1 "Always" Is the Load-Bearing Word

A postcondition holds for **every** execution that satisfied the precondition, not for the typical one. Consider:

```
/** Precondition:  0 <= index < items.size()
 *  Postcondition: returns the item at index; the list is unchanged
 */
```

"The list is unchanged" is a real promise with teeth. It rules out an implementation that quietly reorders the list for efficiency, and a caller is entitled to rely on it. Postconditions constrain the implementer, which is what makes them useful.

### 4.2 A Complete Contract

```
/** Removes the first occurrence of target from the list.
 *
 *  Precondition:  the list has been initialized
 *  Postcondition: if target was present, it has been removed and
 *                 every later element has shifted down one position;
 *                 if target was absent, the list is unchanged.
 *                 Returns true if a removal occurred, false otherwise.
 */
public boolean removeFirst(String target)
```

Read what that contract does

It handles **both branches** — found and not found — so the caller never has to guess. It describes the shift, which is the part that surprises people. And it says what the return value means, rather than leaving `true` to be interpreted. Nothing in it mentions how the removal is implemented, which is the point: the contract survives a rewrite of the body.

### 4.3 Four Contracts Worth Studying

The same method body can carry very different contracts, and the contract is what a caller actually programs against.

**A method that may fail.**

```
/** Precondition:  none
 *  Postcondition: returns the index of target in data, or -1 if
 *                 target does not appear. data is unchanged.
 */
```

No precondition, so every input is legal — which forces the postcondition to say what happens when the search fails. A contract with no precondition must cover more cases, not fewer.

**A method that mutates.**

```
/** Precondition:  amount > 0 and amount <= balance
 *  Postcondition: balance has been reduced by amount.
 *                 No value is returned.
 */
```

Nothing comes back, so the entire postcondition is about the object's attributes — the second of the two forms the course names. Note that the overdraft case is pushed into the precondition, so this method never has to consider it.

**The same method, defensive instead.**

```
/** Precondition:  amount > 0
 *  Postcondition: if amount <= balance, balance has been reduced by
 *                 amount and true is returned; otherwise the balance
 *                 is unchanged and false is returned.
 */
```

Same job, different division of responsibility. The overdraft moved out of the precondition and into the postcondition, so now the method must handle it and the caller must inspect the result. Neither version is more correct — but only one of them lets a caller ignore the return value safely.

**A method with a subtle promise.**

```
/** Precondition:  words.length > 0
 *  Postcondition: returns the longest string in words. If several
 *                 are tied for longest, the earliest one is returned.
 */
```

The tie rule is the whole value of this contract. Without it, two correct-looking implementations disagree on the same input, and neither is wrong. Whenever a method's answer could reasonably be more than one thing, the contract is where you pick.

Where to put a condition

Ask who is better placed to handle it. If the caller naturally knows — they built the array, they chose the index — make it a precondition. If only the method can discover it, it belongs in the postcondition as a described outcome.

## 5Reading Contracts on the Exam

Free-response questions hand you preconditions and postconditions constantly, and they are instructions rather than decoration.

What a stated precondition buys you

If a question says *Precondition: `nums.length > 0`*, you must **not** spend code checking for an empty array. It is guaranteed. Writing the check is not rewarded, costs time, and can suggest you did not read the contract. The converse is also true: with no such precondition, an empty case may be exactly what the question is testing.

### 5.1 A Worked Reading

```
/** Precondition:  scores.length > 0 and every score is in 0..100
 *  Postcondition: returns the number of scores strictly above avg
 */
public static int countAbove(int[] scores, double avg)
```

| What it tells you | What follows |
| --- | --- |
| Length is at least 1 | No empty-array handling. A loop is safe immediately |
| Values are 0–100 | No range validation. Ignore impossible values |
| "strictly above" | `>`, not `>=`. A score equal to the average is not counted |
| Returns a count | An `int`, and zero is a legitimate answer |

Four decisions made before writing a line, all from two comment lines. That is what reading the contract is worth.

### 5.2 A Second Reading, With a Trap

```
/** Precondition:  grid is a rectangular 2D array with at least one row
 *  Postcondition: returns the sum of the values in the first column
 */
public static int firstColumnSum(int[][] grid)
```

"At least one row" is guaranteed. "Rectangular" is guaranteed. What is **not** guaranteed is that any row has a column — a grid of one empty row satisfies both stated conditions and still has no first column to sum.

What to do about it

On an exam, write to the contract as stated and do not invent extra defenses — the graders' solution will not have them. But notice the gap, because "the precondition does not actually rule out the failing case" is itself a favorite question. A contract is only as strong as the conditions it names.

### 5.3 When Comments Go Wrong

Three failure modes worth recognizing, because each looks like documentation:

| Failure | What it looks like | Why it is worse than nothing |
| --- | --- | --- |
| **Stale** | The comment describes the previous version of the method | The compiler never checks it, so it can be wrong indefinitely while looking authoritative |
| **Restating** | `i++; // increment i` | Adds reading time, adds nothing, and trains readers to skip comments |
| **Vague contract** | "Precondition: input is valid" | Looks like a promise, but no caller can tell whether they satisfied it |

The asymmetry to hold on to

Code that is wrong usually announces itself — it fails a test, it throws, it produces a visibly bad answer. A comment that is wrong announces nothing, ever. That asymmetry is the entire reason this topic is examinable: documentation is the one part of a program with no automatic check on its truthfulness.

## 6Check Yourself

*A method is documented "Precondition: the array is sorted in increasing order." A caller passes an unsorted array and gets a wrong answer. Is the method broken?*

Response

No. The precondition was not satisfied, so the method made no promise about this call. The fault is the caller's. The method is also not required to detect the violation — there is no expectation that a method checks its preconditions.

*Is "Postcondition: the method runs quickly" a well-formed postcondition?*

Response

No, on two counts. It is not checkable — "quickly" has no test. And it describes neither of the two things a postcondition may describe: the value returned, or the state of the object's attributes. Speed is a design goal, not a postcondition.

*Which comment form would you use to document a public method so that other programmers see it in generated API documentation?*

Response

`/** */`, the Javadoc form. A plain block comment `/* */` would be equally invisible to the compiler but would not be collected into the documentation.

*A comment says a method returns the largest value. The body actually returns the smallest. What does the compiler do?*

Response

Nothing — comments are ignored by the compiler and never executed, so the program compiles and runs, returning the smallest value. The damage is entirely human: every caller who trusted the comment now has a bug that the code does not reveal. This is why a wrong comment is worse than no comment.

## 7Summary

| Idea | What to remember |
| --- | --- |
| `//` | Single-line comment |
| `/* */` | Block comment across multiple lines |
| `/** */` | Javadoc — generates API documentation |
| All three | Ignored by the compiler, never executed |
| **Precondition** | True just before the call, for the method to behave as expected |
| Checking preconditions | There is *no expectation* the method checks them |
| **Postcondition** | Always true after execution — the return value, or the object's attributes |
| Broken precondition | Caller's fault; the method promised nothing |
| On the exam | A stated precondition means do not write the check |

The habit

Before writing a method, finish two sentences: **"the caller must guarantee…"** and **"afterwards it will be true that…"**. If you cannot finish the first, the method accepts anything and must handle everything. If you cannot finish the second, the method does not do anything worth calling.

FiveStudy · AP Computer Science A · 2025–26

U1T8 · Documentation with Comments · LO 1.8.A
