التعليقات
في هذا الدرس 11 موضوعات
هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.
Lesson Overview
Your programs now compile and print. But code is also a message to other people: the teammate who reads it next month, and you, six months from now, with no memory of why you wrote it. A comment is text in your source file that the compiler skips completely. It is the margin note on the recipe card, such as "use cold butter, warm butter makes it greasy."
This lesson covers the three comment styles in Java, what each is for, and, most importantly, how to decide when a comment is worth writing. Many beginners write comments that repeat the code. Good comments say what the code cannot say by itself.
Why this matters: professional code is read many times more than it is written. A short, honest comment explaining a surprising decision can save a teammate an hour, and a wrong or stale comment can cost a day.
This lesson builds on Lessons 1 to 3: you can write a class, main, and print statements, so you have something to comment.
Learning Objectives
By the end of this lesson you will be able to:
- Write a single-line (
//), a multi-line (/* ... */), and a Javadoc (/** ... */) comment. - Explain that the compiler ignores comments and that they do not change what the program prints.
- Say where a Javadoc comment goes and what it is used for.
- Use a comment to temporarily switch a line of code off.
- Tell a comment that explains why from one that only repeats what.
- Avoid the common comment errors: unclosed multi-line comments and nested multi-line comments.
Written Explanation
The three kinds of comment
The Java Language Specification defines two kinds of comment: the traditional comment /* ... */ and the end-of-line comment // .... Javadoc comments are a special use of the traditional form. In practice you will meet three styles:
| Style | Written as | Ends at | Typical use |
|---|---|---|---|
| Single-line | // text | The end of the line | A short note, or a note beside a statement |
| Multi-line | /* text */ | The first */ | A longer note across several lines |
| Javadoc | /** text */ | The first */ | Documentation placed right before a class, method, or field |
Here they all are in one program:
/**
* Prints a one-line welcome for new students.
* Written for the first-program lesson.
*/
public class Notes {
/**
* Starts the program and prints the welcome line.
*
* @param args command-line values (not used here)
*/
public static void main(String[] args) {
// Single-line comment: the compiler ignores everything after the slashes.
System.out.println("Welcome!"); // a comment can also follow a statement
/* A multi-line comment can
span as many lines as you need. */
System.out.println("// this is text, not a comment");
// System.out.println("Not printed");
}
}Compile and run it. The output is:
Welcome!
// this is text, not a commentNotice what is not printed: nothing from the comments, and nothing from the commented-out last statement.
Rules the compiler follows
From the specification:
- Everything inside a comment is ignored. It is not checked for spelling, correctness, or anything else.
- Comments are not recognised inside text in quotes. That is why
"// this is text, not a comment"prints in full: the slashes are part of the string. - A traditional comment does not nest. The first
*/ends it, even if you wrote another/*inside. This makes a surprising error:
/* outer start
/* inner */
still outer? */The comment ends at the first */ after the word inner. The text still outer? */ is then treated as code, and javac reports an error on it. The exact message depends on the JDK version. When you see an odd error right after a comment, look for this.
- A multi-line comment that you forget to close swallows everything after it up to the next
*/, or to the end of the file, which gives an error such as "unclosed comment".
Javadoc comments
A Javadoc comment starts with /**. The javadoc tool that ships with the JDK reads these comments and generates HTML documentation pages for your classes and methods. The comment is placed immediately before the declaration it describes: a class, a method, or a field. The first sentence is the summary. Lines starting with @param and @return describe parameters and return values in a structured way.
The main method above has an @param args line. Do not worry about the other tags yet. You will use @param and @return more when you write methods that take values and return results.
A Javadoc comment is still a comment, so the compiler ignores it. The difference is that a tool treats it as documentation. Use /** */ for descriptions of classes and methods, and // for notes inside method bodies.
Switching a line off
Putting // at the front of a line comments it out. The compiler skips it, but the code stays in the file. Developers do this to test the program without a statement, or to keep an old version beside a new one while experimenting. Used briefly, it is fine. Do not leave large blocks of commented-out code in finished programs: version control tools, which you will meet later, remember the old version for you, and dead code makes files harder to read.
(Most IDEs provide a shortcut that comments or uncomments the selected lines. The key combination differs by IDE and operating system, so look for "Comment with Line Comment" in your IDE's Code menu.)
When is a comment useful?
A comment is useful when it tells the reader something the code does not already say. Compare:
// print the text
System.out.println("Receipt printed");The comment repeats the code. It adds nothing, and if someone changes the code but forgets the comment, the comment becomes a lie. Now compare:
// The printer driver needs two blank lines at the end, or the last line is cut off.
System.out.println();
System.out.println();This comment explains why. Nobody could work that out from the two statements alone.
A short rule: explain why, not what. Good reasons to write a comment:
- A decision that is not obvious ("we print twice because the printer cuts the last line").
- A warning about a trap ("do not change this order, the report depends on it").
- A summary of what a class or method is for (this is the Javadoc comment).
- A pointer to where an unusual rule comes from (a requirement, a ticket, a document).
Bad reasons: repeating the line below, explaining syntax that the language already makes clear, or apologising for confusing code. If code needs a long comment to be understood, consider rewriting the code to be clearer, with better names and a simpler layout.
Comments also need maintenance. When the code changes, update or delete the comment. A comment that contradicts the code is worse than no comment.
Examples
Example 1: the three styles on one program (simple)
/** A tiny program that prints a greeting. */
public class Greet {
public static void main(String[] args) {
// Print the greeting.
System.out.println("Hello");
/* Printing twice
on purpose. */
System.out.println("Hello again");
}
}Output:
Hello
Hello againRemove all the comments and the program behaves identically. Comments change what readers know, not what the program does.
Example 2: a useless comment and a useful one (practical)
public class Banner {
public static void main(String[] args) {
// print Welcome
System.out.println("Welcome");
// Two blank lines: the support team's console view hides the last two lines.
System.out.println();
System.out.println();
}
}The first comment is useless: the line right below it already says that. The second explains a reason that is not visible in the code. In a code review, you would ask for the first to be deleted and you would keep the second.
Example 3: commenting out to find a problem (realistic)
You have a program that prints three lines, but the second line shows the wrong text, and you want to see if the problem is in that line or somewhere else:
public class Debug {
public static void main(String[] args) {
System.out.println("Step 1");
// System.out.println("Step 2: " + 3 + 4);
System.out.println("Step 2 (new): " + (3 + 4));
System.out.println("Step 3");
}
}Output:
Step 1
Step 2 (new): 7
Step 3The old line is switched off while the new line is tested. When you are happy, you delete the commented-out line rather than leaving it behind, and the final code has no extra noise.
Backend Insight
In real backend projects, Javadoc comments on public classes and methods are part of how teams document code that other teams use. A comment before a method typically says what it does, what its inputs mean, and what it returns. Tools can turn those comments into browsable HTML pages, which is the purpose of the javadoc tool.
Inside a method, the useful comments are about why: a business rule ("orders over 100 get free shipping, per the March pricing policy"), a workaround for an outside system ("this service sometimes answers twice, so ignore duplicates"), or a warning about performance. Those facts live in people's heads and in tickets, and a short comment keeps them next to the code they affect.
Stale comments are a real source of bugs. When the rule in the code changes and the comment still describes the old rule, people trust the comment and make the wrong change. This is why teams prefer fewer, truthful comments.
Common Mistakes
Mistake 1: Commenting what, not why
- Weak:
// add 1above a line that adds 1. - Better: a comment on the reason, such as
// skip the header row.
Mistake 2: Nesting multi-line comments
- Incorrect:
/* outer /* inner */ still outer */ - Correct: use
//for the inner note, or a single/* ... */.
The first */ ends the comment, so the rest becomes code and breaks compilation.
Mistake 3: Forgetting to close /*
A missing */ makes the compiler treat the rest of the file as comment, or report an unclosed comment. When errors appear far below a comment, check that it is closed.
Mistake 4: Putting a Javadoc comment in the wrong place
A Javadoc comment belongs right before the class or method it describes. Placed elsewhere, such as in the middle of a method body, it is just an ordinary comment, and a documentation tool will not attach it to anything.
Mistake 5: Leaving old comments and dead code behind
Delete commented-out code and outdated notes when you finish. They confuse readers and drift away from the truth.
Exercises
Try each exercise yourself before opening the solutions. Hands-on items must be done on your machine.
Level A: Foundation
A1. Write one example of each comment style: single-line, multi-line, and Javadoc.
A2. Does a comment change what a program prints? Does a // inside a quoted string start a comment?
A3. Which comment is more useful, and why? (a) // print the total above System.out.println("Total: 12"); (b) // The accountant wants the total in a separate line. above the same line.
Level B: Application
B1. Add a Javadoc comment to the class Hello, a single-line comment explaining why one statement exists, and a multi-line comment at the top of main. Compile and run it to show that the output has not changed.
B2. What does this print? Check by running it.
public class Off {
public static void main(String[] args) {
System.out.println("A");
// System.out.println("B");
System.out.println("C"); // System.out.println("D");
}
}B3. Rewrite each weak comment as a why comment, inventing a plausible reason: (a) // loop (b) // set the name (c) // print the header. Because we have not met loops or variables, you only need to write the new comment text.
Level C: Challenge
C1. The following program does not compile. Explain why, and fix it in two different ways without losing any note.
public class Twice {
public static void main(String[] args) {
/* note one
/* note two */
end of notes */
System.out.println("Done");
}
}C2. Take a program you wrote in an earlier lesson and review its comments. Delete any that only repeat the code, and rewrite or add at least one that explains a reason. Say in two sentences how the file is easier to read.
أظهر الحلول
A1. For example: // a note, then /* a note across lines */, then /** Describes the class. */.
A2. No. The compiler ignores comments, so the output is the same with or without them. No, inside a quoted string the slashes are just characters. "// text" prints as written.
B1. For example:
/** Prints a greeting for the first lesson. */
public class Hello {
public static void main(String[] args) {
/* The program starts here.
It prints one line and ends. */
// The text matches the course's sample output.
System.out.println("Hello, Java!");
}
}It prints Hello, Java!, the same as without the comments.
B2. It prints A and C on separate lines. The B line is commented out. The text after // on the C line is ignored, so D is not printed.
B3. Sample answers: (a) // retry up to three times because the network drops short requests (b) // use the name from the sign-up form, not the account name (c) // the header must come first or the parser rejects the file. Any believable why is fine.
C1. The comment ends at the first */, which is after note two. The remaining text end of notes */ is treated as code and causes a compile error. Fix 1: use // for the inner note: /* note one */ then // note two then // end of notes. Fix 2: write one multi-line comment with no inner /*: /* note one, note two, end of notes */.
C2. Answers vary. A good answer names a deleted "what" comment, a new "why" comment, and says the reader now sees reasons they could not get from the code, with less noise.
Mini Challenge
Take your Card program from the previous lesson and add three comments: a Javadoc comment before the class saying what the card is for, a single-line comment explaining one why (for example, why the border has this length), and one multi-line comment that lists the fields on the card. Then add one deliberately useless comment, and write on a note why you will delete it.
Check your work: the program prints the same lines as before, the Javadoc comment sits directly above public class Card, and your why comment would still make sense to a stranger.
Summary & Next Lesson
Key takeaways
//comments to the end of the line,/* ... */can span lines, and/** ... */is a Javadoc comment placed before a class, method, or field.- The compiler ignores comments, so they never change the output. Comment markers inside quoted text are just text.
- Multi-line comments do not nest, and an unclosed one hides the rest of the file.
- The
javadoctool turns Javadoc comments into HTML documentation. - Write comments that explain why, keep them true when the code changes, and delete old code instead of leaving it commented out.
Next lesson
Now that you can write and annotate programs, the next lesson, "Reading compiler errors", teaches how to read what javac says when something is wrong, and how to fix common errors from the message alone.
Self-check
- Which comment style is used for Javadoc?
- Does
/* a /* b */ c */work as one comment? Why or why not? - What does a comment that explains why give the reader?
- Does
System.out.println("// hi");print anything? - Where does a Javadoc comment for a method go?
أظهر الإجابات
/** ... */.- No. The comment ends at the first
*/, soc */is left as code. - A reason that the code itself does not show, such as a business rule or a workaround.
- Yes, it prints
// hi, because the slashes are inside a string and not a comment. - Immediately before the method declaration.
References
- Oracle, The Java Language Specification, Java SE 21, section 3.7 (Comments). It defines the traditional comment and the end-of-line comment, says traditional comments do not nest, and says comments are not recognised inside string literals.
- Oracle,
javadoccommand reference, JDK 21. It says the tool reads declarations and documentation comments from source files and generates HTML API documentation. The/** ... */form and the@paramand@returntags are standard practice, but that page does not itself define the comment syntax. - Example outputs were produced with JDK 21 on Windows. I could not run the
javadoctool in my environment, so the HTML-generation claim rests on the documentation page only. The advice on "why" comments and stale comments is general engineering practice, not from an official source.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.