Comments in Java
Comments are annotations in the source code that are ignored by the compiler. They are used to explain code, making it easier to understand and maintain. Java supports three types of comments:
-
Single-Line Comments
Single-line comments start with two forward slashes (//). Any text between // and the end of the line is considered a comment.
Example:
public class Main { public static void main(String[] args) { // This is a single-line comment System.out.println("Hello, World!"); // This comment is after a statement } }
-
Multi-Line Comments
Multi-line comments start with
/*
and end with*/
. Any text between these symbols is considered a comment, and it can span multiple lines.Example:
public class Main { public static void main(String[] args) { /* This is a multi-line comment It spans multiple lines and can be very useful for detailed explanations */ System.out.println("Hello, World!"); } }
-
Documentation Comments Documentation comments start with
/**
and end with*/
. They are used to generate documentation for your code using tools like Javadoc. These comments are typically placed before class, method, or field declarations.Example:
/** * The Main class implements an application that * simply prints "Hello, World!" to the standard output. */ public class Main { /** * This is the main method which makes use of printHello method. * @param args Unused. */ public static void main(String[] args) { System.out.println("Hello, World!"); } /** * This method is used to print a hello message. * @param name This is the only parameter to printHello method. * @return Nothing. */ public void printHello(String name) { System.out.println("Hello, " + name); } }
Summary
- Single-Line Comments (
//
): Used for brief comments. - Multi-Line Comments (
/* ... */
): Used for longer comments that span multiple lines. - Documentation Comments (
/** ... */
): Used for generating external documentation with tools like Javadoc.
- Single-Line Comments (