DevAcademia
C++C#CPythonJava
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz
  • Java Basics

  • Java Introduction
  • Java Get Started
  • Java Syntax
  • Java Output
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Type Casting
  • Java Operators
  • Java Strings
  • Java If...Else
  • Java Switch Statement
  • Java Loops
  • Java Math
  • Java Arrays
  • Java Date
  • Java OOP

  • Java Classes/Objects
  • Java Class Attributes
  • Java Class Methods
  • Java Constructors
  • Java Destructors
  • Java this Keyword
  • Java Modifiers
  • Java Non Modifiers
  • Java Encapsulation
  • Java Packages & API
  • Java Inheritance
  • Java Polymorphism
  • Java Super Keyword
  • Java Inner Classes
  • Java Exception Handling
  • Java Abstraction
  • Java Interfaces
  • Java Enums
  • Java User Input
  • Java Quiz

  • Java Fundamentals Quiz

Loading Java tutorial…

Loading content
Java BasicsTopic 7 of 59
←PreviousPrevNextNext→

Java Comments - Complete Guide

Introduction to Java Comments

Comments in Java are notes within the source code that are ignored by the compiler. They help developers explain logic, provide documentation, or temporarily disable code without affecting execution.

Java supports three kinds of comments: single-line (//), multi-line (/* */), and documentation (/** */). Each has a specific use case and syntax.

Single-Line Comments

Single-line comments start with // and continue to the end of the line. They are best for short explanations or disabling one line of code.

Example
public class SingleLineComments {
    public static void main(String[] args) {
        // Declare and initialize variable
        int age = 25; // store age

        // System.out.println("This line is disabled");

        double total = calculateTotal(100, 0.1); // apply 10% discount
        System.out.println("Final total: " + total);
    }

    // Method applies discount
    public static double calculateTotal(double amount, double discount) {
        return amount - (amount * discount);
    }
}
ℹ️ Note: Use single-line comments for quick notes or to disable individual statements.

Multi-Line Comments

Multi-line comments begin with /* and end with */. They are used for longer explanations or temporarily disabling blocks of code.

⚠️ Warning: Do not nest multi-line comments. Java does not allow /* inside another /* */.
Example
public class MultiLineComments {
    /*
     * Example: multi-line comment spanning several lines.
     * Useful for detailed notes.
     */
    public static void main(String[] args) {
        /*
        This block calculates an average.
        Disabled temporarily for debugging.
        double avg = (85 + 92 + 78) / 3.0;
        char grade = calculateGrade(avg);
        System.out.println("Average: " + avg + ", Grade: " + grade);
        */

        System.out.println("Program still runs even with large blocks commented out.");
    }

    /*
    Determines grade based on average.
    */
    public static char calculateGrade(double average) {
        if (average >= 90) return 'A';
        else if (average >= 80) return 'B';
        else if (average >= 70) return 'C';
        else if (average >= 60) return 'D';
        else return 'F';
    }
}

Documentation Comments (Javadoc)

Documentation comments (/** */) are used to create external documentation with the Javadoc tool. They can include tags for structured information.

Example
/**
 * Represents a simple BankAccount.
 * Demonstrates Javadoc usage.
 *
 * @author John Doe
 * @version 1.0
 * @since 2024
 */
public class BankAccount {
    private double balance;

    /**
     * Constructs a BankAccount with initial balance.
     * @param initialBalance starting balance
     * @throws IllegalArgumentException if initialBalance < 0
     */
    public BankAccount(double initialBalance) {
        if (initialBalance < 0) {
            throw new IllegalArgumentException("Balance cannot be negative");
        }
        this.balance = initialBalance;
    }

    /**
     * Deposits money.
     * @param amount to deposit
     * @return new balance
     * @throws IllegalArgumentException if amount < 0
     */
    public double deposit(double amount) {
        if (amount < 0) throw new IllegalArgumentException("Negative deposit not allowed");
        balance += amount;
        return balance;
    }

    /**
     * Withdraws money.
     * @param amount to withdraw
     * @return new balance
     * @throws IllegalArgumentException if amount < 0 or exceeds balance
     */
    public double withdraw(double amount) {
        if (amount < 0) throw new IllegalArgumentException("Negative withdrawal not allowed");
        if (amount > balance) throw new IllegalArgumentException("Insufficient funds");
        balance -= amount;
        return balance;
    }

    /**
     * Returns balance.
     * @return current balance
     */
    public double getBalance() {
        return balance;
    }
}
ℹ️ Note: Run `javadoc BankAccount.java` to generate documentation.

Common Javadoc Tags

TagDescriptionExample
@authorSpecifies author@author John
@versionIndicates version@version 1.2
@sinceIntroduced version@since JDK 1.8
@paramDescribes method parameter@param name user name
@returnDescribes return value@return true if success
@throwsDocuments thrown exception@throws IOException if file missing
@seeLinks to related item@see OtherClass
@deprecatedMarks method deprecated@deprecated use newMethod()

Commenting Best Practices

  • ✅ Explain WHY, not WHAT
  • ✅ Keep comments updated
  • ✅ Use Javadoc for public APIs
  • ✅ Avoid redundant comments
  • ✅ Mark TODOs or future improvements
  • ✅ Write clear and concise notes
  • ✅ Maintain consistent style
  • ✅ Remove old commented-out code

When to Use Comments

Effective comment strategy includes:

• Complex algorithms: explain logic

• Business rules: document reasoning

• API documentation: use Javadoc for public classes and methods

• Debugging: temporarily disable code

• TODO notes: mark pending work

• Warnings: highlight potential issues

Test your knowledge: Java Comments - Complete Guide
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Java BasicsTopic 7 of 59
←PreviousPrevNextNext→