1. Reference Guide

Term Definition / Example College Board Requirement
Comment Text for people that the compiler ignores Unit 1, Topic 1.8, p. 40
Single-line comment // comments out the rest of one line: int x = 5; // starting value Unit 1, Topic 1.8, p. 40
Block comment /* */ comments out everything between the markers, across lines Unit 1, Topic 1.8, p. 40
Javadoc comment /** */ before a class or method, used to build API documentation Unit 1, Topic 1.8, p. 40
Precondition What must be true before a method is called. The method does not have to check it Unit 1, Topic 1.8, p. 40
Postcondition What is always true after the method runs: the return value or the object’s new state Unit 1, Topic 1.8, p. 40
  • Commented-out code does not run, so a method inside /* */ does not exist as far as the compiler is concerned
  • Comments explain why the code does something; the code already shows what it does

Javadoc Template and Tags


/**
 * One sentence saying what the method does.
 *
 * Precondition: what the caller must make true first.
 * Postcondition: what is true when the method returns.
 *
 * @param name what the parameter means and its allowed values
 * @return what the method gives back
 */
Tag Describes
@param One parameter: its meaning and allowed values
@return The value the method returns
@throws An exception the method might throw
@author, @version Who wrote a class and which version it is (class comments)

Documentation Best Practices

Do Don’t
Be specific: “returns the average of the scores, from 0.0 to 100.0” Be vague: “processes the data”
Document edge cases: what happens with 0, negatives, or an empty input Document a getter whose name already says everything
Update the comment when the code changes Let the comment describe old code

Deciding Whether to Document

  • The method has rules for its inputs → write them as preconditions
  • The method changes an object or can return different kinds of answers → write the postcondition for each case
  • The name and signature already say everything (getName()) → a comment adds nothing
  • The code is commented out → it does not run; delete it or bring it back

College Board Requirements

AP CSA Unit 1, Topic 1.8 Documentation with Comments. Quoted from the course and exam description (College Board, 2025, p. 40):

  • “Comments are written for both the original programmer and other programmers to understand the code and its functionality, but are ignored by the compiler and are not executed when the program is run. Three types of comments in Java include /* */, which generates a block of comments; //, which generates a comment on one line; and /** */, which are Javadoc comments and are used to create API documentation.”
  • “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… A postcondition is a condition that must always be true after the execution of a method.”

Reference: College Board, AP Computer Science A Course and Exam Description (2025), Unit 1, Topic 1.8, p. 40.


2. Real-Life Application

The Comment That Became Famous

The Unix operating system’s source code from the 1970s contains a comment that programmers still quote: “You are not expected to understand this.” It sat above a few lines that switched the computer between running programs. Dennis Ritchie, one of its authors, later explained that the lines relied on a subtle trick that was hard to explain, and later versions of Unix replaced it. Everyone guess: if those lines had a bug, how would the next programmer know what they were supposed to do?

Real Case What Happened Java Idea in This Lesson
Unix source code (1975) A comment admitted the code was hard to follow, but did not say what it had to do A good comment states the rules: preconditions and postconditions
Java’s own API pages Every page on Oracle’s Java documentation site is generated from Javadoc comments /** */ plus @param and @return
A team project A teammate calls your method with a negative number A precondition tells them that is not allowed
AP free-response questions Each method comes with a comment that states its preconditions and what it must do Reading the comment is part of answering the question

The takeaway: code says how. Documentation says what the method promises and what it needs, so the next person can use it without guessing.


3. Tech Talk

Learning Objective: Write single-line, block, and Javadoc comments, and describe a method with its preconditions and postconditions.

Success Criteria: You can document a method with @param and @return, state its preconditions and postconditions, and explain why a simple getter does not need a comment.

Java has three kinds of comments, and the compiler ignores all of them:


int x = 5;     // single line: the rest of the line is a comment
/* block: everything between the
   markers is a comment */
/** Javadoc: describes the class or method right below it */

A method’s documentation is a contract. The precondition is the caller’s side: what must be true first. The postcondition is the method’s side: what will be true after it runs.


Code Examples

A. A method’s contract. The GradeCalculator class documents its parameters, return value, and conditions

The comment says what the method needs and promises. Anyone can call finalGrade without reading its body:


@param homework the average homework score, from 0.0 to 100.0
@return the weighted final grade, from 0.0 to 100.0

Terminology:

Javadoc is a /** */ comment placed right before a method or class. Tools read it to build pages like Java’s own API documentation.


Code Runner Challenge

Read the Javadoc, predict the grade, then run it

View IPYNB Source
// CODE_RUNNER: Read the Javadoc, predict the grade, then run it
public class GradeCalculator {
    /**
     * Calculates a weighted final grade: homework 30%, tests 50%, participation 20%.
     *
     * Precondition: every score is from 0.0 to 100.0.
     * Postcondition: the result is from 0.0 to 100.0.
     *
     * @param homework the average homework score
     * @param tests the average test score
     * @param participation the participation score
     * @return the weighted final grade
     */
    public static double finalGrade(double homework, double tests, double participation) {
        return homework * 0.3 + tests * 0.5 + participation * 0.2;
    }

    public static void main(String[] args) {
        System.out.println("Final grade: " + finalGrade(80.0, 90.0, 100.0));
    }
}

GradeCalculator.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

B. When to document. The BankAccount class documents withdraw and leaves getBalance alone

withdraw has rules, two possible outcomes, and a change to the object, so it gets a full contract. getBalance is obvious from its name, so it gets none:


public double getBalance() { return balance; }   // no comment needed

Terminology:

Postcondition describes every outcome. Here that means both the true path (the money is taken) and the false path (nothing changes).


Code Runner Challenge

Predict both withdrawals from the postcondition, then run it

View IPYNB Source
// CODE_RUNNER: Predict both withdrawals from the postcondition, then run it
public class BankAccount {
    private double balance;

    public BankAccount(double startingBalance) {
        balance = startingBalance;
    }

    /**
     * Takes money out of the account if there is enough.
     *
     * Precondition: amount is greater than 0.
     * Postcondition: if amount is no more than the balance, the balance goes down by
     * amount and the method returns true; otherwise the balance is unchanged and the
     * method returns false.
     *
     * @param amount the amount to withdraw
     * @return true if the money was withdrawn, false if the balance was too low
     */
    public boolean withdraw(double amount) {
        if (amount > balance) {
            return false;
        }
        balance -= amount;
        return true;
    }

    public double getBalance() {
        return balance;
    }

    public static void main(String[] args) {
        BankAccount account = new BankAccount(500.0);
        System.out.println("Withdraw 100: " + account.withdraw(100.0) + ", balance " + account.getBalance());
        System.out.println("Withdraw 900: " + account.withdraw(900.0) + ", balance " + account.getBalance());
    }
}

BankAccount.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Hacks & Practice Tasks


Lesson: CSA 1.8 Documentation with Comments
MCQ 1.8: <paste the copied result line, such as 3/4 | answers: B,C,A,D>
Popcorn: Javadoc with @param, @return, precondition, and postcondition, method renamed, runs and prints (yes/no); predicted result = <p>; actual = <a>
Homework Hack 1: compiler error read = <the error line>, sum documented, check prints true (yes/no)
Homework Hack 2: canEnroll documented and fixed to match it, all four checks print true (yes/no)
Homework Hack 3: GradeBook class and method documented, both checks print true (yes/no)
Reflection: written in the box under Hack 3 (yes/no)

Submission Safety Rules (Read First)

  • One class per cell, ending with ClassName.main(null);.
  • Label the homework hacks 1 through 3.
  • Every Javadoc you write states a precondition and a postcondition.
  • Do not add comments to simple getters; say why in your reflection instead.
  • Run each Java cell and leave the output showing.
  • Include your MCQ score.
  • Use ## headings or smaller.

Popcorn Hack (In-Class)

3-minute challenge: the comment on doSomething tells the reader nothing. Replace it.

  1. Rename doSomething to a name that says what it does, and update the call in main
  2. Replace the // comment with a Javadoc comment that has a one-sentence summary, a precondition, a postcondition, @param nums, and @return
  3. Predict what Result: prints in the Popcorn checker under the runner before you run
  4. Run the cell. When every check passes, copy the checker’s line into your submission notes

Do not change what the method computes.

Code Runner Challenge

Rename the method, write its Javadoc, predict the result, then run it

View IPYNB Source
// CODE_RUNNER: Rename the method, write its Javadoc, predict the result, then run it
// Practice #1 - Try it yourself first!
public class PoorDocumentation {
    // Does stuff with numbers
    public static int doSomething(int[] nums) {
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0 && nums[i] % 2 == 0) {
                result += nums[i];
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -4};
        System.out.println("Result: " + doSomething(numbers));
    }
}

PoorDocumentation.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Before you press Run, predict this output. Read the method body to see which numbers it keeps.

    Pass every check to finish the Popcorn Hack.

    4. MCQ Check

    4 questions, one at a time. Answer, check, then go to the next one. At the end, copy the score line into your submission notes.

    5. Homework Hack

    Task: Do all three hacks. Hack 1 starts with a compiler error on purpose: run it, read the error, then fix it. The other starters compile, so you can run the initial version and compare its incorrect output with the expected output. Keep going until every check prints true.

    Solution Skeleton:

    Hack 1: Commented-Out Code (5 minutes)

    Comments are ignored. main calls sum, but sum is inside a block comment, so the compiler cannot find it. Run it and read the error. Then take sum out of the comment, give it a Javadoc with @param and @return, and run until the check prints true.

    Code Runner Challenge

    Run it to read the compiler error, bring sum back with a Javadoc, then run until the check prints true.

    View IPYNB Source
    // CODE_RUNNER: Run it to read the compiler error, bring sum back with a Javadoc, then run until the check prints true.
    public class CommentedOutHack {
        /*
        public static int sum(int a, int b) {
            return a + b;
        }
        */
    
        public static void main(String[] args) {
            System.out.println("5 + 10 = " + sum(5, 10));
            System.out.println(sum(5, 10) == 15);
        }
    }
    CommentedOutHack.main(null);
    
    Lines: 1 Characters: 0
    Output
    Click "Run" in code control panel to see output ...

    Hack 2: Document the Contract, Then Match It (5 minutes)

    Preconditions and postconditions. The school’s rule is: a student can enroll when the course is not full, the student has the prerequisite, and the total credits stay at 18 or fewer. Write a Javadoc for canEnroll that states this rule as its postcondition, with a precondition about the credit values. The code does not follow the rule yet: fix it so it matches your documentation.

    Code Runner Challenge

    Write the Javadoc for canEnroll, then fix the code to match it so all four checks print true.

    View IPYNB Source
    // CODE_RUNNER: Write the Javadoc for canEnroll, then fix the code to match it so all four checks print true.
    public class EnrollmentHack {
        // TODO: replace this line with a Javadoc: summary, precondition, postcondition, @param for each parameter, @return
        public static boolean canEnroll(int currentCredits, int courseCredits, boolean courseFull, boolean hasPrerequisite) {
            // TODO: this ignores the prerequisite and allows 19 credits; make it match your postcondition
            return !courseFull && currentCredits + courseCredits <= 19;
        }
    
        public static void main(String[] args) {
            System.out.println(canEnroll(15, 3, false, true) == true);    // exactly 18 credits
            System.out.println(canEnroll(16, 3, false, true) == false);   // 19 credits
            System.out.println(canEnroll(10, 4, true, true) == false);    // course is full
            System.out.println(canEnroll(10, 4, false, false) == false);  // no prerequisite
        }
    }
    EnrollmentHack.main(null);
    
    Lines: 1 Characters: 0
    Output
    Click "Run" in code control panel to see output ...

    Hack 3: Document a Class (10 minutes)

    Combined. Write a class-level Javadoc for GradeBook: what it is for, one usage example, @author, and @version. Then write a full Javadoc for finalGrade and implement it as documented: homework counts 25% and tests count 75%. Leave getStudentName without a comment. After both checks print true, answer the reflection below the cell.

    Code Runner Challenge

    Document the class and finalGrade, implement finalGrade, and run until both checks print true.

    View IPYNB Source
    // CODE_RUNNER: Document the class and finalGrade, implement finalGrade, and run until both checks print true.
    public class GradeBookHack {
        // TODO: class-level Javadoc for GradeBook (purpose, usage example, @author, @version)
        static class GradeBook {
            private String studentName;
    
            public GradeBook(String studentName) {
                this.studentName = studentName;
            }
    
            public String getStudentName() {
                return studentName;
            }
    
            // TODO: Javadoc with a precondition, a postcondition, @param for both scores, and @return
            public double finalGrade(double homeworkAverage, double testAverage) {
                return 0.0;  // TODO: homework is 25%, tests are 75%
            }
        }
    
        public static void main(String[] args) {
            GradeBook book = new GradeBook("Ada");
            System.out.println(book.getStudentName() + ": " + book.finalGrade(90.0, 80.0));
            System.out.println(book.finalGrade(90.0, 80.0) == 82.5);
            System.out.println(book.finalGrade(100.0, 100.0) == 100.0);
        }
    }
    GradeBookHack.main(null);
    
    Lines: 1 Characters: 0
    Output
    Click "Run" in code control panel to see output ...

    Reflection #1

    You documented finalGrade but not getStudentName. In a few sentences, explain how you decide whether a method needs a Javadoc comment, and why documentation matters more on a team project than on a solo one.

    Words: 0 Characters: 0

    Grading Plan (1 Point Total)

    Part Points What earns the points
    Popcorn 0.2 The method is renamed and has a Javadoc with a summary, precondition, postcondition, @param, and @return, and it still prints the same result. The Popcorn checker line is in the notes.
    MCQ 0.2 4 correct. 0.15 for 2 or 3, 0.1 if every question was answered.
    Homework Hack 1 0.15 The compiler error is recorded, sum is out of the comment with a Javadoc, and the check prints true.
    Homework Hack 2 0.2 The Javadoc states the enrollment rule as a postcondition, the code is fixed to match it, and all four checks print true.
    Homework Hack 3 0.25 Class and method Javadocs are complete, getStudentName has no comment, both checks print true, and the reflection is answered with a concrete example.
    Total 1.0  

    Quick Validation Checklist

    • Each cell ends with ClassName.main(null); and shows output.
    • Popcorn checker line in the notes.
    • MCQ score in the notes.
    • Every Javadoc you wrote has a precondition and a postcondition.
    • No comment on a simple getter.
    • Every homework check prints true.

    6. LxD Cycle Process

    Empathize: Students treat comments as an afterthought, added at the end to satisfy a rubric. They skip documentation on the methods that need it and over-document getters that do not. They also confuse a precondition with code that checks the precondition.

    Define:

    • POV: CSA students need to see documentation as a contract between the method and its caller, because AP free-response questions and real teammates rely on it to know what a method needs and promises.
    • Learning Goal: Students will write //, /* */, and Javadoc comments, state preconditions and postconditions, and decide when documentation is needed.

    Ideate:

    • HMW Question: How might we get students to document why and what a method promises, instead of restating the code?
    • HMW Question: How might we show that code and its documentation have to agree?
    • Activity: Rewrite a useless comment as a Javadoc, bring back commented-out code, then document an enrollment rule and fix the code so it matches.

    Prototype:

    • A reference guide with a Javadoc template, runnable contract and when-to-document examples, a documentation Popcorn Hack with a checker, an MCQ knowledge check, three scaffolded homework hacks with self-checking output, a reflection, and a grading rubric.
    • Peer review found that an earlier example did not compile and that preconditions appeared in prose long before they appeared in real Javadoc, so every example now compiles and shows its contract inside the comment.
    • Excellence means a specific, accurate contract, with code that does what the comment promises.

    Test:

    • Ask peers in peer review to complete the practice without additional explanation.
    • Observe whether peers write the precondition and postcondition before they edit code, and whether they leave simple getters uncommented.
    • Compare your lesson with another that is posted.
    • Use the findings to revise any instruction or rubric criterion that did not guide students clearly.
    • On submission, collect evidence from runner output, MCQ results, AI grading and student explanations.
    • After teaching, grading and analysis, come back and revise lesson to complete teaching cycle for continuous improvement.

    7. References/Citations

    College Board. (2025). AP Computer Science A course and exam description [Effective fall 2025]. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description-effective-fall-2025.pdf

    Knuth, D. E. (1984). Literate programming. The Computer Journal, 27(2), 97–111. https://doi.org/10.1093/comjnl/27.2.97

    Lions, J. (1996). Lions’ commentary on UNIX 6th edition, with source code. Peer-to-Peer Communications. (Original work published 1977)

    Submit Assignment

    This submits the code from this lesson's code runner(s) below as a Gist for automatic review. Save each runner with its 💾 button before submitting.

      Need to update a submission later? Open the submissions dashboard.