JAVA BASICS
Java comments
Comments help explain what code does and make it easier to read. The Java compiler does not execute comments, so you can use them for notes to other readers or to temporarily disable a line of code during testing.
What are comments for?
A good comment explains a reason, a decision or a non-obvious program rule. It is not a Java statement and does not change the program’s output. Comments are especially useful when several people work on the same project or when you return to your code after a long time.
- explain a more complex piece of code;
- record an important assumption or the reason for a decision;
- leave a brief note for another developer;
- temporarily disable a line of code during a test.
Single-line comments
A single-line comment starts with two forward slashes //. Java ignores everything from these characters to the end of the line.
You can place a comment on its own line before the code it explains:
// This line prints a greeting
System.out.println("Labas, pasauli!");You can also write a short comment at the end of the same line as the code:
System.out.println("Labas, pasauli!"); // Print the textAn end-of-line comment should not obscure the code itself. If the explanation is longer, move it to a separate line or use a block comment.
Multi-line comments
A block comment starts with /* and ends with */. All text between these markers is ignored, even when it spans several lines.
/* The following statement prints a greeting
to the program console. */
System.out.println("Labas, pasauli!"); This type of comment suits longer explanations. Do not forget the closing markers */ — otherwise, the compiler may treat the following program code as part of the comment or report an error.
Temporarily disabling code
During a small test, a comment can temporarily prevent a line from running. In the following example, only the first output statement will execute:
System.out.println("Pagrindinis variantas");
// System.out.println("Bandomasis variantas");Leaving large blocks of unused code in comments for a long time is not recommended. Version control can preserve the old code while the project keeps only the version it currently needs.
Which comment type should you choose?
//is suitable for a short note or an explanation of one line./* ... */is suitable for a longer explanation spanning several lines.- Comment on things that clear variable, method and class names cannot express on their own.
- When code changes, check whether the nearby comment is still correct.