Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Documentation with Comments

Lesson ~10 min read 8 MCQs

In simple terms: In simple terms, comments are notes in your code for humans to read. They explain what the code does, but the computer completely ignores them when running the program.

Why this matters

Imagine you and your friend Marcus are building a massive, custom PC. You spend a weekend carefully routing cables, installing components, and tweaking settings. You label a few key cables with masking tape. A month later, Marcus wants to upgrade the graphics card, but you’re away at a debate tournament. Without your notes, he’s lost. Which cable goes where? What was that specific setting you used in the BIOS? The project grinds to a halt.

Code is the same way. When you write a program, you're not just giving instructions to a computer; you're leaving a blueprint for other people (and your future self!). Comments are the labels and notes in that blueprint. They explain the why behind your code, making it understandable, maintainable, and less of a headache to revisit weeks or months later.

Today, we'll learn how to write effective comments and use them to create clear "contracts" for our methods.

The difference between code and comments: one is for the computer, the other for humans.

Concept overview

flowchart TD
    A[Start: Programmer wants to call a method] --> B{Are all preconditions met?};
    B -- Yes --> C[Call the method];
    C --> D[Method code executes];
    D --> E[Postconditions are now true];
    E --> F[End];
    B -- No --> G[Do not call the method, or expect undefined behavior];
    G --> F;
This diagram shows a flowchart of the "method contract." It starts with a programmer checking if a method's preconditions are met. If yes, the method is called, it executes, and its postconditions become true. If no, the method should not be called.

Core explanation

Welcome to one of the most important habits of a professional programmer: documenting your code. It might not seem as exciting as writing a cool new feature, but trust me, it's a skill that will save you and your teammates countless hours of frustration.

Why Bother with Comments?

Code is read far more often than it is written. You might write a method once, but you, your classmates, or your future colleagues might read it dozens of times. Comments are notes you leave inside your source code that are completely ignored by the compiler. They don't run, they don't slow your program down, and they have zero effect on the output. Their only purpose is to help humans understand what's going on.

How the compiler processes code versus comments.

Think of it like a recipe. The code is the list of ingredients and the step-by-step instructions. The comments are the helpful notes you'd scribble in the margin: "Use a non-stick pan for easier cleanup!" or "Chill the dough for at least an hour for best results." The notes don't change the recipe, but they make it much easier to follow and get a great result.

The Three Types of Java Comments

Java gives us three ways to write comments.

  1. Single-Line Comments: // This is your go-to for short, quick notes. Anything after the // on the same line is a comment.

    double price = 100.0;
    double salesTax = 0.0825; // Using the sales tax for Dallas, TX
    double finalPrice = price * (1 + salesTax);
  2. Multi-Line (Block) Comments: /* ... */ When you need more space, you can use a block comment. It starts with /* and ends with */. Everything in between is ignored. These are great for longer explanations or for temporarily "commenting out" a chunk of code while you're testing something else.

    /*
    This block of code calculates the final price of an item.
    We are assuming a standard item and not accounting for
    any special discounts or tax-exempt statuses.
    The tax rate is hard-coded for now.
    */
    double price = 100.0;
    double salesTax = 0.0825;
    double finalPrice = price * (1 + salesTax);
  3. Javadoc Comments: `/ ... */** This is the professional standard. Javadoc comments look similar to block comments but start with/**`. They are special because a tool called Javadoc can read them and automatically generate clean, professional-looking documentation for your code (an API). This is how the official Java documentation you'll look up all year is made!

The subtle but important difference between Javadoc and regular block comments.
```java
/**
 * Calculates the final price of an item including sales tax.
 * @param price The initial price of the item before tax.
 * @param taxRate The sales tax rate as a decimal (e.g., 0.0825 for 8.25%).
 * @return The final price including tax.
 */
public double calculateFinalPrice(double price, double taxRate) {
    return price * (1 + taxRate);
}
```
Notice the `@param` and `@return` tags. These are special Javadoc tags that clearly identify the method's parameters and what it returns.

The Method Contract: Preconditions and Postconditions

Now for two of the most important concepts in documentation: preconditions and postconditions. Think of them as a contract between the person who writes a method and the person who calls it.

This is where many students get stuck, so let's use an analogy. Imagine a gumball machine.

  • Precondition
    You must insert a quarter ($0.25). This is a condition that must be true before you can use the machine. The machine assumes you will do this. It doesn't check your pockets for a quarter beforehand.
  • Postcondition
    A gumball is dispensed. This is the condition that is guaranteed to be true after you've successfully used the machine (i.e., met the precondition).

In code, it's the same idea:

Preconditions

A precondition is a condition that must be true before a method is called for it to work correctly. It's a rule for the caller of the method.

For our calculateFinalPrice method, a precondition would be that price and taxRate cannot be negative. The method assumes it will receive valid inputs.

This is the critical part: The method itself is not expected to check if the precondition is true. The responsibility is on the programmer using the method to provide valid data. If you call the method with a negative price, its behavior is undefined—it might crash, it might return a weird number, but it's not the method's fault, because the contract was broken.

Postconditions

A postcondition is a condition that is guaranteed to be true after the method has finished running (assuming the preconditions were met). It describes the outcome.

For calculateFinalPrice, the postcondition is that the method returns a double value representing the original price plus the calculated tax. It could also describe a change to an object's state. For example, if a withdraw method is called on a BankAccount object, a postcondition would be that the account's balance has been reduced.

Pre- and postconditions are typically written inside a Javadoc comment block to make the "contract" crystal clear.

/**
 * Calculates the final price of an item including sales tax.
 *
 * PRECONDITION: price >= 0 and taxRate >= 0.
 * POSTCONDITION: Returns the price including tax.
 *
 * @param price The initial price of the item before tax.
 * @param taxRate The sales tax rate as a decimal.
 * @return The final price including tax.
 */
public double calculateFinalPrice(double price, double taxRate) {
    return price * (1 + taxRate);
}

By documenting your code this way, you make it robust, predictable, and easy for others to use correctly.

Comparing the three types of Java comments.

See it in action

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    Worked examples

    Let's walk through how to apply these documentation concepts in practice.

    Example 1: Documenting a Player's Score Update

    Problem: You're creating a Player class for a game. You have a method increaseScore that adds points to the player's total score. Write the complete Javadoc documentation for this method, including pre- and postconditions.

    Solution Walkthrough:

    1. 1
      Identify the Goal
      The method increaseScore takes an integer points and adds it to the player's currentScore.
    2. 2
      Think About the "Contract"
      • Precondition
        What must be true for this to make sense? We probably shouldn't be able to add negative points with this method; that should be a different method like decreaseScore. So, a good precondition is that points must be a non-negative number.
      • Postcondition
        What happens after the method runs? The player's currentScore will have been increased by the points value. The method doesn't return anything (void), so the postcondition is all about the change in the object's state.
    3. 3
      Write the Javadoc
      We'll use a /** ... */ block. We'll state the purpose, list the pre- and postconditions, and use the @param tag to describe the points parameter.
    public class Player {
        private int currentScore;
        private String username;
    
        // ... constructor and other methods ...
    
        /**
         * Increases the player's score by a given number of points.
         *
         * PRECONDITION: points >= 0
         * POSTCONDITION: this.currentScore is increased by the value of points.
         *
         * @param points The non-negative number of points to add to the score.
         */
        public void increaseScore(int points) {
            // The method assumes the precondition is met.
            // It does not check if points is negative.
            this.currentScore += points;
        }
    }
    • What the method does: "Increases the player's score."
    • The rule she must follow: "I must pass in a non-negative number of points." (Precondition)
    • The guaranteed result: "The player's score will go up." (Postcondition)

    Example 2: Documenting a Circle's Area Calculation

    Problem: You have a Circle class with a method to calculate its area. The radius is stored as an instance variable. Document the getArea method.

    Solution Walkthrough:

    1. 1
      Identify the Goal
      The getArea method calculates and returns the area of the circle using the formula A = πr².
    2. 2
      Think About the "Contract"
      • Precondition
        Does this method take any parameters? No. So the precondition must be about the state of the Circle object itself. For the area to be valid, the circle's radius must have been initialized to a non-negative value.
      • Postcondition
        What is the result? The method will return a double that is the calculated area of the circle. The state of the Circle object itself (its radius) does not change.
    3. 3
      Write the Javadoc
    public class Circle {
        private double radius;
    
        /**
         * Constructs a new Circle with a given radius.
         * @param initialRadius The radius of the circle.
         */
        public Circle(double initialRadius) {
            this.radius = initialRadius;
        }
    
        /**
         * Calculates the area of the circle.
         *
         * PRECONDITION: The circle's radius is >= 0.
         * POSTCONDITION: Returns the calculated area of the circle.
         *
         * @return The area of the circle as a double.
         */
        public double getArea() {
            // Math.PI is a built-in constant for pi
            return Math.PI * this.radius * this.radius;
        }
    }
    The 'contract' flow of preconditions and postconditions.

    Try it yourself

    Time to practice your documentation skills.

    1. 1
      Rectangle Area
      Below is a method that calculates the area of a rectangle. Write a complete Javadoc comment block for it. Include @param tags, an @return tag, and appropriate pre- and postconditions.
      public double getRectangleArea(double length, double width) {
          return length * width;
      }

      Hint: What must be true about length and width before the method is called? What does the method promise to return?

    2. 2
      Class Roster
      Imagine a method addStudent(Student newStudent) for a Course object. The course has a maximum capacity of 30 students. Identify a key precondition and postcondition for this method. You don't need to write the code, just the pre- and postcondition statements. Hint: Think about the state of the Course object. What must be true about the roster before you can add a student? What is true about the roster after a student has been successfully added?
    Tracing a method call with preconditions and postconditions in mind.