University College of Applied SciencesProgramming 1
العربية
Lecture 2 · 100 min

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

  1. Explain what a comment does and why the compiler ignores it
  2. Write a single-line comment and a multi-line comment
  3. Write a documentation comment with author, version and date tags
  4. Spot and fix an unclosed comment error
  5. Print formatted text using escape sequences
In this lecture
  1. Comments make code clear to the next reader
  2. A comment is a note in code that the compiler ignores
  3. Comments explain code, remind you, and pause a line
  4. Comments stay in high-level code, not machine code
  5. A single-line comment runs from // to the line's end
  6. Multi-line comments explain a passage or disable lines
  7. Documentation comments use tags that javadoc reads
  8. NetBeans generates documentation pages in one command
  9. Three types of comments, each with its own use
  10. Inside quotes, // is printed text, not a comment
  11. An unclosed /* comments out the rest of the file
  12. A good comment explains why, not what the code says
  13. Escape sequences start with \ and print special characters
  14. print does not move to a new line, and \" does not close the text
  15. Final exercise: document a program, print an ID card
  16. Review questions
Part one: comments

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);
    }
}
Output
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);
    }
}
Output
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.

Single-line

Runs to the end of the line.

// comment
Multi-line

Spans one or more lines.

/* comment */
Documentation

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
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

Explain the code

Classmates and your instructor understand what each part does.

Remind yourself

Return weeks later and still understand your program.

Disable temporarily

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");
    }
}
Expected output
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.

LevelExampleDescription
High levelJavaWritten by us, includes comments
Low levelLOADClose to the processor, no comments
Machine language0101Zeros 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

  1. Type the code and run itIn the lab press F6; here use the Run button or Ctrl+Enter.
  2. Predict: does the comment appear in the output?
  3. Delete // from line 3 and run
  4. 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);
    }
}
Output
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);
    }
}
Compiler message';' expected
Show 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);
    }
}
Output
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.
Long explanation

A passage too long for one line.

Disable several lines

Test the program without them.

File header

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");
    }
}
Output
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
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

LineMeaning
/**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 AliName of the program's author
* @version 1.0Program version number
* @since 2020-09-25Date 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!");
    }
}
Output
Hello World!

NetBeans generates documentation pages in one command

  1. Open HelloWorld.javaFrom the project tree in the Projects area.
  2. Type /** above the class, then press EnterNetBeans completes the comment skeleton. Fill in the description and tags.
  3. 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)
What you see in the Output window when the command succeeds.

Three types of comments, each with its own use

TypeWhen to use itSyntax
Single-lineShort note on one line of code// comment
Multi-lineLong explanation, or disabling several lines/* comment */
DocumentationDescribing 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?

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
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
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");
    }
}
Compiler messageunclosed comment
Show the fix
public class Unclosed {
    public static void main(String[] args) {
        /* print a welcome message */
        System.out.println("Welcome");
    }
}
Output
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");
    }
}
Compiler messagenot a statement
Show 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");
    }
}
Output
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

Explain why

Write why you added the line, not what the code literally says.

Keep it short

A short, clear line beats a long paragraph.

Keep it updated

If you change the code, change the comment with it.

Which comment is the best?

Part two: escape sequences

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.

SequenceMeaningInside the stringOutput
\nNew line"Ali\nSara"Ali, then Sara on a new line
\tTab"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\"");
    }
}
Output
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");
    }
}
Output
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\");
    }
}
Compiler messageunclosed string literal
Show the fix
public class Quote {
    public static void main(String[] args) {
        System.out.println("Hi");
    }
}
Output
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

    }
}
Expected output
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

    }
}
Expected output
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?

Why did all the code turn gray after typing this line?

/* start of program

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
Output
A	B
// A

Why? Inside text, \t prints a tab, and // is ordinary text, not a comment.