CodeBlanks Logo Icon CodeBlanks

Comments

Learn single-line (//) and multi-line (/* */) comments.

Why write comments?

Comments are text that Java ignores but explains the code to humans. Comments help you remember what code does later and help others understand it.

A single-line comment starts with //. Everything from the sign to the end of the line is a comment:

// This is a comment
System.out.println("Hello");

A multi-line comment is wrapped in /* */. A documentation comment /** */ is used for the javadoc tool.

Practice Add a comment and println

Print Welcome to the screen with println. Add a // Greeting message comment above it.

Sample solution

Main.java
// Greeting message
System.out.println("Welcome");

Expected output

Welcome

When should you write comments?

Comments are best used to explain why code is written a certain way. But instead of commenting every line, it is better to pick descriptive variable and method names.

A good comment explains the step of a complex calculation, the reason for an external dependency, or why a hack is needed. A bad comment just repeats what the code does line by line.

Documentation comments (/** */) are written for public methods and classes; javadoc generates HTML docs from them.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the comment line

Question
// This line is a ____
Answer
// This line is a comment

Explanation: A line starting with // is a comment.

2 Which of these is a valid comment?

  • // Greeting message //
  • // Greeting message Correct answer
  • ** Greeting message **
  • /* Greeting message

Explanation: A single-line comment starts with //.

3 Match the comment types

Term Meaning
// Single line
/* */ Multi-line
/** */ Documentation
javadoc Doc tool

All lessons in Beginner