Learn Java (Lesson 2: Comments)

Masroor Khan
2 min readJan 31, 2023

--

How and why to use comments in java with examples

Photo by Clément Hélardot on Unsplash

Introduction:

Comments are lines of text in a Java program that are ignored by the compiler and are used to add explanations, notes, or annotations for the code. They help to make the code more readable and understandable for both the programmer and other people who may read the code later on.

There are two types of comments in Java:

Single-line comments: These comments start with two forward slashes (//) and continue until the end of the line. They are used to add a brief explanation to a single line of code.
Example:

// This line calculates the sum of two numbers
int sum = num1 + num2;

Multi-line comments: These comments start with /* and end with */. They can be used to add explanations to multiple lines of code.
Example:

/*
This section of the code calculates the average of three numbers
by dividing the sum of the numbers by 3.
*/
int average = (num1 + num2 + num3) / 3;

Using comments in Java can help in several ways:

Improving code readability: Comments make the code easier to understand by providing explanations of the code's purpose and behavior.

Debugging: Comments can be used to mark parts of the code that are causing errors or need to be fixed.

Documentation: Comments can be used to document the code, making it easier for others to understand the logic behind it.

Maintenance: Comments can be used to remind the programmer of certain details that might be forgotten later on, making it easier to maintain the code.

In conclusion, comments are an important part of writing clean and maintainable code in Java. They should be used through out the code to provide explanations, notes, or annotations for the code.

In the next lesson, we will discuss about taking Input with Scanner in Java. So don’t forget to follow and let me know if you have any suggestions.

--

--

Masroor Khan

Software and web developer with a passion to learn and teach