Lesson Completion
Back to course

Comments in Java: Documenting Your Code

Beginner
10 minutesβ˜…4.7Java

1. The Hook (The "Byte-Sized" Intro)

  • In a Nutshell: 3 types: Single-line (//), multi-line (/* */), Javadoc (/** */ with @param, @return, @throws).
  • Purpose: Explain WHY (not WHAT).
  • Best practices: Don't state obvious, keep updated, explain complex logic, document public APIs.
  • Javadoc: Generates HTML documentation (javadoc *.java).
  • When to comment: Complex algorithms, business rules, edge cases, NOT self-explanatory code.
  • Golden rule: Good code > comments. Write clear code first, comment when needed!

Think of recipe. Single-line comment = quick note ("add salt"). Multi-line = detailed tip (paragraph). Javadoc = published cookbook (formal documentation). Good comment = "Why high heat?" (explains reason). Bad comment = "Heat pan" (obvious)!


2. Conceptual Clarity (The "Simple" Tier)

πŸ’‘ The Analogy

  • Single-line comment: Sticky note (quick reminder)
  • Multi-line comment: Margin notes (detailed explanation)
  • Javadoc: User manual (professional documentation)
  • Good comment: Why button is red (reasoning)
  • Bad comment: Button is red (obvious)

3. Technical Mastery (The "Deep Dive)

java
// =========================================== // 1. SINGLE-LINE COMMENTS (//) // =========================================== // This is a single-line comment int age = 25; // Age of the user // Comments are ignored by compiler // int x = 10; // This line won't execute // Multiple single-line comments // Line 1 of comment // Line 2 of comment // Line 3 of comment // =========================================== // 2. MULTI-LINE COMMENTS (/* */) // =========================================== /* This is a multi-line comment. It can span multiple lines. Useful for longer explanations. */ int count = 0; /* * Alternative style (more readable) * Each line starts with * * Common in professional code */ double price = 19.99; /* Can also be on single line */ String name = "Alice"; // =========================================== // 3. JAVADOC COMMENTS (/** */) // =========================================== /** * Calculates the area of a rectangle. * * @param length the length of the rectangle * @param width the width of the rectangle * @return the area (length Γ— width) * @throws IllegalArgumentException if length or width is negative */ public double calculateArea(double length, double width) { if (length < 0 || width < 0) { throw new IllegalArgumentException("Dimensions must be positive"); } return length * width; } /** * Represents a student in the system. * * <p>Each student has a unique ID, name, and GPA. * Use {@link StudentService} to manage students.</p> * * @since 1.0 * @author John Doe * @version 2.0 */ public class Student { private String id; private String name; private double gpa; /** * Creates a new student with the given details. * * @param id the student's unique identifier * @param name the student's full name * @param gpa the student's grade point average (0.0 to 4.0) */ public Student(String id, String name, double gpa) { this.id = id; this.name = name; this.gpa = gpa; } /** * Gets the student's GPA. * * @return the GPA value between 0.0 and 4.0 */ public double getGpa() { return gpa; } } // Common Javadoc tags: // @param - Parameter description // @return - Return value description // @throws or @exception - Exception description // @see - Reference to related class/method // @since - Version when added // @deprecated - Mark as deprecated // @author - Author name // @version - Version number // =========================================== // 4. GOOD COMMENTS (Explain WHY) // =========================================== // βœ… GOOD: Explains business logic // Apply 10% discount for orders over $100 // to encourage bulk purchases if (orderTotal > 100) { discount = orderTotal * 0.10; } // βœ… GOOD: Explains workaround // Retry 3 times to handle transient network failures // See ticket #1234 for details for (int i = 0; i < 3; i++) { try { sendRequest(); break; } catch (NetworkException e) { if (i == 2) throw e; } } // βœ… GOOD: Explains non-obvious algorithm // Use binary search for O(log n) performance // List must be sorted! int index = Collections.binarySearch(sortedList, target); // βœ… GOOD: Explains magic number // Wait 30 seconds for database connection timeout // as per AWS RDS recommendations int timeout = 30_000; // milliseconds // =========================================== // 5. BAD COMMENTS (State the Obvious) // =========================================== // ❌ BAD: States what code does (obvious!) // Increment i by 1 i++; // ❌ BAD: Redundant // Loop through all students for (Student student : students) { // ... } // ❌ BAD: Outdated (code changed, comment didn't!) // Returns the user's age public String getName() { // ❌ Returns name, not age! return name; } // ❌ BAD: Commented-out code (delete it!) // int x = 10; // String oldMethod() { } // ❌ BAD: Obvious getter/setter documentation /** * Gets the name. * @return the name */ public String getName() { return name; // ❌ Comment adds no value } // =========================================== // 6. WHEN TO COMMENT // =========================================== // βœ… Complex algorithms // Sliding window technique for substring search // Time: O(n), Space: O(k) where k = pattern length // βœ… Business rules // Tax calculation varies by state: // CA: 7.25%, NY: 4%, TX: 6.25% // βœ… Non-obvious edge cases // Handle leap year: February has 29 days if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) { days = 29; } // βœ… Temporary hacks/workarounds // TODO: Replace with proper authentication once OAuth is set up // Temporary hardcoded credentials for demo // βœ… API documentation (public methods) /** * Searches for a user by email address. * ... */ public User findByEmail(String email) { } // ❌ Self-explanatory code (DON'T comment!) // Calculate total double total = price * quantity; // ❌ Obvious! // Get user name String name = user.getName(); // ❌ Obvious! // =========================================== // 7. GENERATING JAVADOC // =========================================== // Command to generate documentation: // javadoc -d docs *.java // This creates HTML documentation in 'docs' folder // Open docs/index.html in browser // Example output: // - Class summary // - Constructor details // - Method summaries with parameters and return types // - Field documentation // =========================================== // 8. SPECIAL COMMENTS (Markers) // =========================================== // TODO: Implement user authentication void login(String username, String password) { // TODO } // FIXME: This causes memory leak, fix ASAP! List<String> cache = new ArrayList<>(); // NOTE: This assumes input is already validated void processData(String data) { // ... } // HACK: Temporary workaround until API v2 is ready String result = workaroundMethod(); // XXX: Review this code, seems inefficient for (int i = 0; i < list.size(); i++) { for (int j = 0; j < list.size(); j++) { // O(nΒ²) algorithm } }

5. The Comparison & Decision Layer

Comment TypeSyntaxUse Case
Single-line//Quick notes, inline explanations
Multi-line/* */Longer explanations, disable code blocks
Javadoc/** */Public API documentation, classes, methods

6. The "Interview Corner" (The Edge)

The "Killer" Interview Question: "When should you add comments?" Answer: Explain WHY, not WHAT!

DO comment:

  • Complex algorithms ("Using sliding window for O(n) solution")
  • Business rules ("10% discount for loyalty members as per policy")
  • Workarounds ("Retry 3x for transient network errorsβ€”ticket #1234")
  • Non-obvious code ("Bitwise AND to check even: n & 1 == 0")

DON'T comment:

  • Obvious code (i++ // increment i ❌)
  • Self-documenting code (getUserName() is clear!)
  • Outdated comments (update or delete!)
  • Commented-out code (delete itβ€”use version control!)
java
// ❌ BAD: States the obvious // Loop through users for (User user : users) { // ... } // βœ… GOOD: Explains WHY // Process users in batches of 100 to avoid // overwhelming the database connection pool for (int i = 0; i < users.size(); i += 100) { processBatch(users.subList(i, Math.min(i + 100, users.size()))); }

Pro-Tips:

  1. Self-documenting code > comments:
java
// ❌ Needs comment double t = p * q * 1.18; // Calculate total with tax // βœ… Self-explanatory double TAX_RATE = 0.18; double totalWithTax = price * quantity * (1 + TAX_RATE);
  1. Javadoc best practices:
java
/** * Transfers money between accounts. * * <p>This operation is atomic and thread-safe. * If transfer fails, both accounts remain unchanged.</p> * * @param from source account (must have sufficient funds) * @param to destination account * @param amount amount to transfer (must be positive) * @throws InsufficientFundsException if from account lacks funds * @throws IllegalArgumentException if amount is negative * @see Account#getBalance() */ public void transfer(Account from, Account to, double amount) { // ... }

Topics Covered

Java FundamentalsJava Syntax

Tags

#java#basics#syntax#variables#data-types#beginner-friendly

Last Updated

2025-02-01