Comments in Java serve the dual purpose of explaining code for better readability and temporarily disabling code execution when experimenting with alternative approaches.
Single-line comments in Java begin with two forward slashes ( // ).
Any text following // until the end of the line is disregarded by Java and will not be executed.
Here’s an example demonstrating the usage of a single-line comment preceding a line of code:
|
In this example, a single-line comment is placed at the end of a line of code.
System.out.println(“Hello World”); // This is a comment |
Multi-line comments in Java are initiated with /* and concluded with */.
Any text enclosed between /* and */ will be disregarded by Java.
Here’s an example demonstrating the usage of a multi-line comment, also known as a comment block, to elucidate the code:
|
The choice between using // or /* */ for comments is yours. Typically, // is used for brief comments, while / * */ is preferred for longer explanations.