In this lesson, we will explore how to use comments in Java to explain and make code more readable. Comments can also be used to prevent code execution when testing alternative implementations.
Single-line Comments
Single-line comments start with two forward slashes (//
). Any text between //
and the end of the line is ignored by Java (will not be executed).
Example:
// This is a single-line comment System.out.println("Hello, Java");
You can also place a single-line comment at the end of a line of code.
Example:
System.out.println("Hello, Java"); // This is a single-line comment
Multi-line Comments
Multi-line comments start with /*
and end with */
. Any text between /*
and */
will be ignored by Java.
Example:
/* This is a multi-line comment that spans multiple lines */ System.out.println("Hello, Java");
Multi-line comments are useful for providing more detailed explanations or temporarily disabling blocks of code during testing.
Choosing Between Single-line and Multi-line Comments
It is up to the developer to choose between single-line and multi-line comments. Typically, single-line comments (//
) are used for brief comments, while multi-line comments (/* */
) are used for longer descriptions.
Additional Information
- Documentation Comments: Java also supports documentation comments, which are multi-line comments that start with
/**
and end with*/
. These comments are used to generate documentation using the Javadoc tool.
Example:
/** * This is a documentation comment * It provides information about the class or method */ public class Example { public static void main(String[] args) { System.out.println("Hello, Java"); } }