3. Comments in Java

Types of Comments

  • Single-line comments begin with // and continue until the end of the line.
  • They are commonly used for short explanations or to temporarily disable code.

// This is a single-line comment
System.out.println("Hello, World!"); // Prints a message to the screen

    
  • Multi-line comments begin with /* and end with */.
  • They allow you to write comments that span multiple lines, making them useful for providing detailed explanations.

/* 
   This is a multi-line comment.
   It can span multiple lines.
*/
System.out.println("Java is fun!");


    
  • Documentation comments are special comments used for generating HTML documentation of a program.
  • They begin with /** and end with */.
  • These comments are commonly used for describing methods and classes in Java.
  • Java’s Javadoc tool can process these comments to generate documentation files for your code.
  • You will learn more about documentation comments in future lessons for now consider a simple example

/**
 * This class represents a simple calculator.
 * It can perform addition and subtraction.
 */
public class Calculator {
    /**
     * Adds two numbers and returns the result.
     */
    public int add(int a, int b) {
        return a + b;
    }
}



    

Pages: 1 2