Comments in Java
Notes for people inside the code, ignored by the compiler
Prepared by: Eng. Badereddin Mohammed Elhalimi · Eng. Mohammed Zuhair Kouhail
By the end of this lecture you will be able to
- Explain what a comment does and why the compiler ignores it
- Write a single-line comment and a multi-line comment
- Write a documentation comment with author, version and date tags
- Spot and fix an unclosed comment error
- Print formatted text using escape sequences
In this lecture
- Comments make code clear to the next reader
- A comment is a note in code that the compiler ignores
- Comments explain code, remind you, and pause a line
- Comments stay in high-level code, not machine code
- A single-line comment runs from // to the line's end
- Multi-line comments explain a passage or disable lines
- Documentation comments use tags that javadoc reads
- NetBeans generates documentation pages in one command
- Three types of comments, each with its own use
- Inside quotes, // is printed text, not a comment
- An unclosed /* comments out the rest of the file
- A good comment explains why, not what the code says
- Escape sequences start with \ and print special characters
printdoes not move to a new line, and\"does not close the text- Final exercise: document a program, print an ID card
- Review questions
Comments make code clear to the next reader
Code without comments
double is a type that holds a decimal number, which the next lecture explains. For now, a and b are just names that hold numbers.
public class Mystery {
public static void main(String[] args) {
double a = 4.5;
double b = 2;
System.out.println(a * b / 2);
}
}4.5
The same code with comments
Run the program, then press "Debug line by line" and press "Next line" several times. Notice that the highlight skips the comment line, because nothing in it runs.
public class Triangle {
public static void main(String[] args) {
// area of a triangle
double a = 4.5; // base
double b = 2; // height
System.out.println(a * b / 2);
}
}4.5
Comments do not change how a program runs: both print 4.5, but the second is faster to understand.
A comment is a note in code that the compiler ignores
A comment is text we write inside a program to explain what the code does. The compiler neither translates nor runs it, and it ignores every character inside, whatever it says.
Runs to the end of the line.
// commentSpans one or more lines.
/* comment */Read by the javadoc tool.
/** comment */The comment holds valid code and some nonsense. What does the program print?
public class Ignored {
public static void main(String[] args) {
// System.out.println("Hidden"); @#$ 123 nonsense
System.out.println("Shown");
}
}Show the output
Shown
Why? Everything after // on that line is ignored by the compiler, so it neither rejects the odd symbols nor runs the print statement.
Comments explain code, remind you, and pause a line
Classmates and your instructor understand what each part does.
Return weeks later and still understand your program.
Turn a line into a comment to test the program without it.
Comments are for people only: the program runs the same way with or without them.
Pause the middle line
Without deleting anything, turn the line that prints Two into a comment so that it is not printed.
public class Pause {
public static void main(String[] args) {
System.out.println("One");
System.out.println("Two");
System.out.println("Three");
}
}One Three
Hint 1
Type // at the start of the line. In NetBeans, you can select the line and press Ctrl + /.
Solution
public class Pause {
public static void main(String[] args) {
System.out.println("One");
// System.out.println("Two");
System.out.println("Three");
}
}Comments stay in high-level code, not machine code
Reminder: your program passes through three levels before the processor runs it.
| Level | Example | Description |
|---|---|---|
| High level | Java | Written by us, includes comments |
| Low level | LOAD | Close to the processor, no comments |
| Machine language | 0101 | Zeros and ones the processor executes |
The compiler removes comments during compilation, so they never reach the .class file. That is why they affect neither the program's speed nor its compiled size.
What does javac produce from a file with comments?
A single-line comment runs from // to the line's end
- Type the code and run itIn the lab press F6; here use the Run button or Ctrl+Enter.
- Predict: does the comment appear in the output?
- Delete
//from line 3 and run - Explain the error message, then restore
//
public class Comments {
public static void main(String[] args) {
// print a welcome message
System.out.println("Welcome");
int x = 5; // comment after code
System.out.println(x);
}
}Welcome 5
We deleted //
This is the result of step 3: the comment has become code. Put // back at the start of the line.
public class Comments {
public static void main(String[] args) {
print a welcome message
System.out.println("Welcome");
int x = 5; // comment after code
System.out.println(x);
}
}';' expectedShow the fix
public class Comments {
public static void main(String[] args) {
// print a welcome message
System.out.println("Welcome");
int x = 5; // comment after code
System.out.println(x);
}
}Welcome 5
Why? Without // the compiler reads the words as code. Its message looks unrelated to the real cause, because it cannot know you meant a comment; it only complains that the words do not form a valid statement.
Multi-line comments explain a passage or disable lines
/*opens the comment and*/closes it, and everything between the two is a comment, however many lines.- We use it when the explanation is long and one line is not enough.
- It is useful for disabling several lines of code at once.
- If you forget to close it, the rest of the file becomes a comment.
A passage too long for one line.
Test the program without them.
Program name, author and date.
A file header and disabled lines
Move the */ to after the line that prints Three. What changes in the output?
/* Program: Counting
Author: Sara Ali
Date: 2026-09-01 */
public class Counting {
public static void main(String[] args) {
System.out.println("One");
/* System.out.println("Two"); */
System.out.println("Three");
}
}One Three
A multi-line comment in the middle of a line. What does the program print?
public class Middle {
public static void main(String[] args) {
System.out.println("A"); /* System.out.println("B");
System.out.println("C"); */ System.out.println("D");
}
}Show the output
A D
Why? The comment starts at /* and ends at */, whatever the lines. The first print is before it and the last is after it.
Documentation comments use tags that javadoc reads
| Line | Meaning |
|---|---|
/** | Opens the documentation comment: a slash, then two asterisks |
* Prints "Hello World!" | Short description of what the program does |
* | Blank line separating the description from the tags |
* @author Ahmed Ali | Name of the program's author |
* @version 1.0 | Program version number |
* @since 2020-09-25 | Date of the program's first release |
*/ | Closes the comment |
The javadoc tool reads these lines and builds documentation pages from them, like the official Java documentation.
A documentation comment in a real program
Run the program, then change @author to your name and @version to 1.1. Does the output change?
/**
* Prints "Hello World!"
*
* @author Ahmed Ali
* @version 1.0
* @since 2020-09-25
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}Hello World!
NetBeans generates documentation pages in one command
- Open
HelloWorld.javaFrom the project tree in the Projects area. - Type
/**above the class, then press EnterNetBeans completes the comment skeleton. Fill in the description and tags. - Choose Run > Generate JavadocThe result appears in the Output window and the pages open in the browser.
Output - HelloWorld (javadoc)
javadoc:
Generating Javadoc...
BUILD SUCCESSFUL (total time: 2 seconds)Three types of comments, each with its own use
| Type | When to use it | Syntax |
|---|---|---|
| Single-line | Short note on one line of code | // comment |
| Multi-line | Long explanation, or disabling several lines | /* comment */ |
| Documentation | Describing the program for javadoc | /** comment */ |
The compiler ignores all three types. They differ in form and in who reads the comment; only the documentation comment is read by javadoc to build documentation pages.
You want your program's description to appear in the documentation pages. Which type do you write?
/* is what marks a documentation comment, and javadoc reads only this type.Inside quotes, // is printed text, not a comment
The comment comes before the statement. What does the program print before the Done line?
public class CommentFirst {
public static void main(String[] args) {
// System.out.println("Hi");
System.out.println("Done");
}
}Show the output
Done
Why? The whole line is a comment, so the print statement does not run and nothing from it appears.
The symbol is inside quotation marks. What does the program print?
public class InQuotes {
public static void main(String[] args) {
System.out.println("// Hi");
}
}Show the output
// Hi
Why? Text between quotation marks prints exactly as written, // included. The compiler recognizes comments only outside quotation marks.
An unclosed /* comments out the rest of the file
Deliberate experiment: we deleted the closing symbol
In NetBeans you get a red mark next to the line number, a red underline at the error, and all the code turns gray. Add the closing symbol at the end of the comment.
public class Unclosed {
public static void main(String[] args) {
/* print a welcome message
System.out.println("Welcome");
}
}unclosed commentShow the fix
public class Unclosed {
public static void main(String[] args) {
/* print a welcome message */
System.out.println("Welcome");
}
}Welcome
Why? The comment has no closing symbol, so the compiler treats everything after it as a comment, to the end of the file. All-gray code in NetBeans signals an unclosed comment.
Do not nest one multi-line comment inside another
We wanted to disable all three lines, but the program does not compile. Delete the first closing symbol.
public class Nested {
public static void main(String[] args) {
/* outer comment
/* inner comment */
this line is outside the comment */
System.out.println("Welcome");
}
}not a statementShow the fix
public class Nested {
public static void main(String[] args) {
/* outer comment
/* inner comment
this line is inside the comment */
System.out.println("Welcome");
}
}Welcome
Why? The first */ ends the whole comment, so whatever follows becomes meaningless code. That is why the compiler's message looks unrelated to the real cause.
A good comment explains why, not what the code says
Write why you added the line, not what the code literally says.
A short, clear line beats a long paragraph.
If you change the code, change the comment with it.
Which comment is the best?
Escape sequences start with \ and print special characters
How do we print a new line, a tab or a quote in text? By putting an escape sequence inside the quotation marks.
| Sequence | Meaning | Inside the string | Output |
|---|---|---|---|
\n | New line | "Ali\nSara" | Ali, then Sara on a new line |
\t | Tab | "Ali\tSara" | A tab between the two names |
\\ | Backslash | "C:\\Java" | Prints C:\Java |
\" | Quotation mark | "\"Hi\"" | Prints Hi in quotation marks |
Try all four sequences
Predict the lines before running, then press "Debug line by line" and watch where the cursor stops after each statement.
public class Escapes {
public static void main(String[] args) {
System.out.println("Ali\nSara");
System.out.println("Ali\tSara");
System.out.println("C:\\Java");
System.out.println("\"Hi\"");
}
}Ali Sara Ali Sara C:\Java "Hi"
- Symbols you need in this lecture: switch the keyboard to English before typing code (Alt+Shift).
- Backslash
\: the key above Enter; every escape sequence starts with it. - Slash
/: the key next to the right Shift. - Asterisk
*: Shift + 8. - Quotation mark
": Shift + the key next to Enter.
print does not move to a new line, and \" does not close the text
print("Hi\n") works like println("Hi")
print prints without moving to a new line. Delete \n from the first line and predict the output before running.
public class PrintNewLine {
public static void main(String[] args) {
System.out.print("Hi\n");
System.out.print("Hello ");
System.out.println("Java");
}
}Hi Hello Java
Error: the string is not closed
We wanted to print just Hi. Delete the extra backslash.
public class Quote {
public static void main(String[] args) {
System.out.println("Hi\");
}
}unclosed string literalShow the fix
public class Quote {
public static void main(String[] args) {
System.out.println("Hi");
}
}Hi
Why? \" means a quotation mark to print, so it does not close the text. The compiler reaches the end of the line with the text still open.
Print the path and the title
Print the two lines shown in the expected output, with one println for each line.
public class PathTitle {
public static void main(String[] args) {
// Print the two lines here
}
}C:\Users\Sara The book "Java"
Hint 1
Every backslash you print needs \\.
Hint 2
Every quotation mark you print needs \".
Solution
public class PathTitle {
public static void main(String[] args) {
System.out.println("C:\\Users\\Sara");
System.out.println("The book \"Java\"");
}
}Final exercise: document a program, print an ID card
- A documentation comment with your name and the program version.
- A single-line comment above each print statement, explaining what it prints.
- Escape sequences: a tab and quotation marks.
The ID card
Write the program so it prints the card as expected: one tab after Name:. You succeed if the card matches and no comment appears in the output.
/**
* Prints a student ID card.
*
* @author Your Name
* @version 1.0
*/
public class Comments {
public static void main(String[] args) {
// Write one comment and one print statement for each line
}
}Name: Ahmed Course: "Programming 1" Version: 1.0
Hint 1
Use \t after Name: and \" around the course name.
Hint 2
Try printing the whole card with one println using \n, then try printing it with three statements.
Solution
/**
* Prints a student ID card.
*
* @author Ahmed Ali
* @version 1.0
*/
public class Comments {
public static void main(String[] args) {
// the student's name, after a tab
System.out.println("Name:\tAhmed");
// the course name, in quotation marks
System.out.println("Course: \"Programming 1\"");
// the program version
System.out.println("Version: 1.0");
}
}Review questions
What does the compiler do with comments?
When do you use a multi-line comment instead of a single-line comment?
/* */ can span several lines, and that is what sets it apart. Comments do not affect speed at all.Why did all the code turn gray after typing this line?
/* start of program
/* is a comment to the end of the file.What does each line print?
public class Review {
public static void main(String[] args) {
System.out.println("A\tB");
System.out.println("// A");
}
}Show the output
A B // A
Why? Inside text, \t prints a tab, and // is ordinary text, not a comment.