Comments
Single-line, multi-line, and documentation comments
Interview Relevant: Writing clean, documented code is crucial
5 min read
Why Write Comments?
Comments explain your code to other developers (and to yourself in the future). They are ignored by the compiler and don't affect program execution. Writing good comments is a sign of professional code.
Types of Comments
1. Single-Line Comments
Start with //. Used for brief explanations:
2. Multi-Line Comments
Start with /* and end with */. Used for longer explanations:
3. JavaDoc Comments
Start with /** and end with */. Special comments that generate documentation:
💡 Best Practice: Use JavaDoc comments for public classes and methods. Use single-line comments for complex logic.
Commenting Best Practices
- Explain WHY, not WHAT. Code shows what, comments explain why.
- Keep comments concise and clear
- Update comments when you change the code
- Avoid obvious comments
- Don't comment out code - delete it if not needed
Code Examples
Single-line comments with //
java
1// This is a single-line comment
2int age = 25; // Comments can also go at the end of a line
3
4// Single comments are perfect for short explanations
5// You can also use multiple single-line commentsMulti-line comments spanning multiple lines
java
1/* This is a multi-line comment
2 It can span across several lines
3 Useful for longer explanations
4 and complex logic descriptions */
5int result = 10 + 20;JavaDoc comments for generating automatic documentation
java
1/**
2 * Calculates the sum of two numbers
3 * @param a the first number
4 * @param b the second number
5 * @return the sum of a and b
6 */
7public int add(int a, int b) {
8 // Method implementation
9 return a + b;
10}Professional commenting with explanations and documentation
java
1/**
2 * Calculate factorial recursively
3 * Algorithm: n! = n * (n-1)!
4 * Used for permutation calculations
5 * @param n input number
6 * @return factorial of n
7 */
8public long factorial(int n) {
9 // Base case
10 if (n <= 1) return 1;
11 // Recursive case: multiply n with factorial of (n-1)
12 return n * factorial(n - 1);
13}Use Cases
- Documenting complex algorithms and logic
- Explaining non-obvious code to team members
- Generating API documentation with JavaDoc
- Marking temporary fixes and TODOs
- Recording assumptions and important notes
Common Mistakes to Avoid
- Writing comments that describe obvious code
- Not updating comments when code changes
- Commenting out code instead of deleting it
- Forgetting JavaDoc comments for public APIs
- Writing novels instead of concise explanations
- Using outdated or misleading comments