AP Computer Science A · Unit 3: Class Creation
3.3 Documentation with Comments
Why comments matter
Comments are text in source code ignored by the compiler, used to explain code to human readers. Good documentation improves readability, helps other programmers (and future you) understand purpose and logic, and is essential for maintaining and debugging large programs.
Two comment syntaxes
Java has two comment types: single-line comments using `//`, which comment out everything to the end of that line, and multi-line (block) comments using `/* ... */`, which can span multiple lines and are often used for longer explanations or file/class headers.
What to document
Well-documented code typically includes comments describing a class's purpose, a method's purpose, parameters, and return value, and clarification of any complex or non-obvious logic. Comments should explain *why*, not just restate *what* the code obviously does.
Key terms
- Comment
- Text in source code ignored by the compiler, used to explain code to human readers.
- Single-line comment
- Begins with //, continues to the end of the line.
- Multi-line (block) comment
- Begins with /* and ends with */, can span multiple lines.
- Why document code?
- Improves readability and helps others (and future you) understand purpose, logic, and design.
- What should comments explain?
- A class's purpose, a method's purpose/parameters/return value, and complex or non-obvious logic — the 'why,' not just the 'what.'
Try an AP-style question
Code
/** Precondition: n >= 0 * Returns the factorial of n. */ public int factorial(int n)
Who is responsible for making sure n >= 0?
- The code that calls the method
- The Java compiler, at compile time
- The method itself, every time
- The JVM, while the program runs
Show the answer
A. Preconditions are the caller's job.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 3.3 free in APrep