Table of Contents

    Comments

    Programming Mastery

    Comments

    Learn what comments are in programming, why programmers use them, different types of comments, and how comments make code easier to understand, debug, document, and maintain.

    What are Comments in Programming?

    Comments are notes written inside source code to explain the program. They are written for humans, not for the computer.

    Comments help programmers understand what the code does, why a certain logic is used, and how different parts of the program work. When a program runs, comments are ignored by the computer, compiler, or interpreter.

    Comments are human-readable explanations written inside code, but they are not executed by the computer.

    Comments are useful in almost every programming language. They are commonly used to explain logic, document important sections, improve readability, and temporarily disable code during testing or debugging.

    Easy Real-Life Example

    Comments as Notes in a Notebook

    Imagine you are solving a math problem in your notebook. Beside the solution, you write a small note explaining why you used a formula. That note does not change the answer, but it helps you understand the solution later.

    In programming, comments work in the same way. Code tells the computer what to do, while comments help humans understand the code.

    Why are Comments Important?

    Comments are important because programs are not only written once; they are also read, tested, updated, debugged, and maintained many times. A programmer may return to the same code after days, weeks, or months. Good comments make the code easier to understand.

    Importance of Comments

    • Comments explain the purpose of code.
    • They help beginners understand program logic.
    • They make code easier to read and maintain.
    • They help other programmers understand your work.
    • They are useful for explaining complex logic.
    • They can temporarily disable code during debugging.
    • They support documentation in professional projects.
    • They improve teamwork and collaboration.

    Simple Example of a Comment

    The following example shows a simple comment written before a line of code.

    // Display a welcome message.
    print("Welcome to Programming")

    Here, the comment explains the purpose of the code. The computer ignores the comment and only executes the actual instruction.

    Types of Comments

    Different programming languages support comments in different ways. However, the most common types of comments are single-line comments, multi-line comments, and documentation comments.

    1

    Single-Line Comments

    Used for short explanations on one line.

    A single-line comment is used when the explanation is short and fits on one line.

    2

    Multi-Line Comments

    Used for longer explanations across multiple lines.

    A multi-line comment is useful when the explanation needs more than one line.

    3

    Documentation Comments

    Used to describe functions, classes, modules, or APIs.

    Documentation comments are used in professional projects to generate or maintain formal documentation.

    Common Comment Styles Across Languages

    Comment symbols may differ depending on the programming language. The table below shows common comment styles.

    Comment Type Common Syntax Used In
    Single-Line Comment // comment C, C++, Java, JavaScript, PHP, C#
    Single-Line Comment # comment Python, Bash, Ruby
    Single-Line Comment -- comment SQL
    Multi-Line Comment /* comment */ C, C++, Java, JavaScript, CSS, PHP, C#
    HTML Comment <!-- comment --> HTML
    Documentation Comment /** comment */ Common in Java, JavaScript, C#, and documentation tools

    1. Single-Line Comments

    A single-line comment is used to write a short explanation on one line. It is best for brief notes.

    Example

    // Store the student's age.
    age = 18
    
    // Display the student's age.
    print(age)

    The comments explain what the code is doing, but they do not affect program execution.

    Python-Style Example

    # Store product price.
    price = 100
    
    # Display product price.
    print(price)

    Some languages, such as Python, use # for single-line comments.

    2. Multi-Line Comments

    A multi-line comment is used when the explanation is longer than one line. It is useful for describing a block of logic or giving a longer note.

    Example

    /*
    This program calculates the total marks
    of three subjects and displays the result.
    */
    
    mathMarks = 80
    scienceMarks = 75
    englishMarks = 85
    
    totalMarks = mathMarks + scienceMarks + englishMarks
    print(totalMarks)

    Multi-line comments are useful when a single-line comment is not enough to explain the logic.

    3. Documentation Comments

    A documentation comment is used to describe important parts of a program such as functions, classes, modules, parameters, and return values.

    Documentation comments are common in professional software development because they help create structured documentation.

    Generic Documentation Comment Example

    /**
     * Calculates the total price of a product.
     *
     * Parameters:
     * price - The price of one product.
     * quantity - The number of products.
     *
     * Returns:
     * The total price.
     */

    This type of comment helps other developers understand how a function or module should be used.

    Comments vs Code

    Comments and code are different. Code is executed by the computer, while comments are ignored.

    Comment Code
    Written for humans. Written for the computer to execute.
    Ignored during execution. Executed by the computer.
    Explains logic or purpose. Performs actual operations.
    // Calculate total marks. total = math + science + english

    Using Comments for Debugging

    Comments can also be used to temporarily disable a line or block of code while testing. This is called commenting out code.

    Example

    print("Line 1")
    
    // print("Line 2")
    
    print("Line 3")

    Output

    Line 1
    Line 3

    The second print statement is ignored because it has been commented out.

    Good Comments vs Poor Comments

    Good comments explain why something is done. Poor comments only repeat what the code already says.

    Poor Comments

    • Repeat obvious code.
    • Are too long without purpose.
    • Are outdated or incorrect.
    • Make simple code look complicated.
    • Explain what is already clear from variable names.

    Good Comments

    • Explain why code exists.
    • Clarify complex logic.
    • Document important decisions.
    • Help future developers understand the code.
    • Stay short, clear, and accurate.

    Poor Comment Example

    // Add number1 and number2.
    sum = number1 + number2

    This comment is not very useful because the code is already easy to understand.

    Better Comment Example

    // Apply bonus marks before calculating the final result.
    totalMarks = totalMarks + bonusMarks

    This comment is more useful because it explains why the value is being updated.

    Best Practices for Writing Comments

    Comments should be helpful, clear, and professional. Too many unnecessary comments can make code messy.

    Recommended Practices

    • Use comments to explain why code exists.
    • Keep comments short and meaningful.
    • Write comments in simple language.
    • Update comments when code changes.
    • Avoid writing comments for every obvious line.
    • Use single-line comments for short notes.
    • Use multi-line comments for longer explanations.
    • Use documentation comments for important functions, classes, or modules.
    • Place comments close to the code they explain.
    • Use clear variable and function names so fewer comments are needed.

    Professional Comment Formatting

    A professional comment should be easy to read and consistent with the coding style of the project.

    Formatting Tips

    • Place important comments on a separate line.
    • Start comment text with a capital letter.
    • End complete comment sentences with a period.
    • Use one space after the comment symbol.
    • Keep comments aligned with related code.
    • Avoid leaving old commented-out code in final programs.

    Good Formatting

    // Calculate the final amount.
    finalAmount = price * quantity

    Poor Formatting

    //calculate final amount
    finalAmount = price * quantity

    Complete Example Using Comments

    The following example shows comments in a language-neutral style.

    /*
    This program calculates the total and average marks
    of a student.
    */
    
    // Store student name.
    studentName = "Ravi"
    
    // Store marks of three subjects.
    mathMarks = 80
    scienceMarks = 75
    englishMarks = 85
    
    // Calculate total marks.
    totalMarks = mathMarks + scienceMarks + englishMarks
    
    // Calculate average marks.
    averageMarks = totalMarks / 3
    
    // Display final result.
    print("Student Name: " + studentName)
    print("Total Marks: " + totalMarks)
    print("Average Marks: " + averageMarks)

    Expected Output

    Student Name: Ravi
    Total Marks: 240
    Average Marks: 80

    Common Beginner Mistakes

    Mistakes

    • Writing too many unnecessary comments.
    • Not updating comments after changing code.
    • Writing comments that repeat obvious code.
    • Using comments instead of writing clear code.
    • Forgetting to close multi-line comments.
    • Leaving old commented-out code in final programs.
    • Writing confusing or incomplete comments.
    • Using comments to hide bad naming or poor structure.

    Better Habits

    • Write comments only where helpful.
    • Keep comments accurate and updated.
    • Use meaningful variable and function names.
    • Use comments to explain complex or important logic.
    • Close multi-line comments properly.
    • Use documentation comments for reusable code.
    • Remove unnecessary commented-out code.
    • Write comments for future readers, not only for yourself.

    Prerequisites Before Learning Comments

    To understand comments properly, students should know a few basic programming concepts.

    Basic Prerequisites

    • Basic understanding of programming.
    • Basic program structure.
    • Statements in programming.
    • Expressions in programming.
    • Keywords and identifiers.
    • Variables and data types.
    • Simple input, process, and output logic.
    • Basic understanding of functions or reusable blocks of code.

    Practice Activity: Add Comments

    This activity helps students practice writing useful comments in a program.

    Task

    Add meaningful comments to the following program logic.
    price = 100
    quantity = 3
    
    totalAmount = price * quantity
    
    print("Total Amount: " + totalAmount)

    Sample Answer

    // Store product price.
    price = 100
    
    // Store product quantity.
    quantity = 3
    
    // Calculate total bill amount.
    totalAmount = price * quantity
    
    // Display total amount.
    print("Total Amount: " + totalAmount)

    Mini Quiz

    1

    What is a comment?

    A comment is a note written inside code to explain the program. It is ignored by the computer during execution.

    2

    Why are comments used?

    Comments are used to explain logic, improve readability, support debugging, and help future maintenance.

    3

    What is a single-line comment?

    A single-line comment is a short comment written on one line.

    4

    What is a multi-line comment?

    A multi-line comment is a longer comment that can span multiple lines.

    5

    Do comments affect program output?

    No. Comments are ignored during execution, so they do not affect program output.

    Interview Questions on Comments

    1

    Define comments in programming.

    Comments are non-executable notes written in source code to explain logic, improve readability, and help maintain the program.

    2

    What are the common types of comments?

    Common types include single-line comments, multi-line comments, and documentation comments.

    3

    How do comments help debugging?

    Comments can temporarily disable lines or blocks of code, helping programmers test and isolate problems.

    4

    What makes a good comment?

    A good comment is clear, short, accurate, and explains the purpose or reason behind the code.

    5

    Should every line of code have a comment?

    No. Comments should be used only where they add value. Clear code does not need unnecessary comments.

    Quick Summary

    Concept Meaning
    Comment A human-readable note written inside code.
    Single-Line Comment A short comment written on one line.
    Multi-Line Comment A longer comment that spans multiple lines.
    Documentation Comment A structured comment used to document functions, classes, modules, or APIs.
    Commenting Out Temporarily disabling code using comments.
    Good Comment Explains why code exists or clarifies complex logic.
    Poor Comment Repeats obvious code or becomes outdated.

    Final Takeaway

    Comments are an important part of writing clean and understandable programs. They do not execute, but they help humans understand the code. In the Programming Mastery Course, students should learn to use comments wisely: explain important logic, support debugging, document reusable code, and make programs easier to read and maintain.

    Programming Fundamentals

    Comments

    Learn what comments are in programming, why they are used, the different types of Java comments, and how comments help make code easier to read, understand, debug, and maintain.

    What are Comments in Programming?

    Comments are notes written inside source code to explain the program. They are written for humans, not for the computer.

    Comments help programmers understand what the code does, why a particular logic is written, and how different parts of the program work. When a program runs, comments are ignored by the compiler or interpreter.

    Comments are human-readable explanations written inside code, but they are not executed by the computer.

    In Java, comments are commonly used to explain code, document classes and methods, and temporarily disable code during testing or debugging.

    Easy Real-Life Example

    Comments as Sticky Notes

    Imagine you are solving a math problem in your notebook. Beside the solution, you write small notes explaining why you used a formula. These notes help you understand the solution later. Comments in programming work in the same way.

    Code tells the computer what to do. Comments tell humans why the code exists or how it works.

    Why are Comments Important?

    Comments are important because programs are often read many times after they are written. A programmer may return to the same code after days, weeks, or months. Good comments make the code easier to understand.

    Importance of Comments

    • Comments explain the purpose of code.
    • They help beginners understand program logic.
    • They make code easier to read and maintain.
    • They help other programmers understand your work.
    • They are useful for documenting complex logic.
    • They can temporarily disable code during debugging.
    • They help create professional documentation using Javadoc.
    • They improve collaboration in team projects.

    Simple Example of a Comment

    The following Java program contains a comment.

    public class Main {
        public static void main(String[] args) {
            // Display a welcome message.
            System.out.println("Welcome to Java");
        }
    }

    Here, the line starting with // is a comment. It explains what the next line of code does.

    Types of Comments in Java

    Java mainly supports three types of comments.

    1

    Single-Line Comment

    Used for short explanations on one line.

    Single-line comments start with //.

    2

    Multi-Line Comment

    Used for longer explanations across multiple lines.

    Multi-line comments start with /* and end with */.

    3

    Documentation Comment

    Used to generate documentation using Javadoc.

    Documentation comments start with /** and end with */.

    Java Comment Syntax Summary

    Comment Type Syntax Best Used For
    Single-Line Comment // comment text Short explanation of one line or one small idea.
    Multi-Line Comment /* comment text */ Long explanation across multiple lines.
    Documentation Comment /** comment text */ Documentation for classes, methods, and APIs.

    1. Single-Line Comments

    A single-line comment is used to write a short explanation on one line. It starts with two forward slashes //.

    // This is a single-line comment.

    Everything written after // on the same line is treated as a comment.

    Example

    public class Main {
        public static void main(String[] args) {
            // Store student age.
            int age = 18;
    
            // Display student age.
            System.out.println(age);
        }
    }

    Output

    18

    The comments explain the purpose of the statements, but they do not affect the output.

    2. Multi-Line Comments

    A multi-line comment is used when the explanation is longer than one line. It starts with /* and ends with */.

    /*
    This is a multi-line comment.
    It can continue for multiple lines.
    */

    Example

    public class Main {
        public static void main(String[] args) {
            /*
            This program calculates the total marks
            of three subjects and displays the result.
            */
    
            int math = 80;
            int science = 75;
            int english = 85;
    
            int total = math + science + english;
    
            System.out.println("Total Marks: " + total);
        }
    }

    Output

    Total Marks: 240

    Multi-line comments are useful when we need to explain a complete section of code.

    3. Documentation Comments

    A documentation comment is a special type of comment used to create documentation for classes, methods, constructors, and fields.

    Documentation comments start with /** and end with */.

    /**
     * This is a documentation comment.
     */

    Example

    /**
     * The Calculator class performs basic arithmetic operations.
     */
    public class Calculator {
    
        /**
         * Adds two numbers and returns the result.
         *
         * @param number1 The first number.
         * @param number2 The second number.
         * @return The sum of number1 and number2.
         */
        public int add(int number1, int number2) {
            return number1 + number2;
        }
    }

    Documentation comments are useful in professional projects because they can describe how classes and methods should be used.

    Common Javadoc Tags

    Documentation comments often use special tags to describe parameters, return values, authors, and versions.

    Tag Purpose Example
    @param Describes a method parameter. @param age The age of the student.
    @return Describes the value returned by a method. @return Total marks.
    @author Specifies the author of the code. @author Rumman
    @version Specifies the version of the class or program. @version 1.0
    @since Specifies from which version the feature exists. @since 1.0

    Comments vs Code

    Comments and code are different. Code is executed by the computer, but comments are ignored.

    Comment Code
    Written for humans. Written for the computer to execute.
    Ignored by the compiler. Compiled and executed.
    Explains logic or purpose. Performs actual operations.
    // Calculate total marks. total = math + science + english;

    Using Comments for Debugging

    Comments can be used to temporarily disable a line or block of code while testing. This is called commenting out code.

    Example

    public class Main {
        public static void main(String[] args) {
            System.out.println("Line 1");
    
            // System.out.println("Line 2");
    
            System.out.println("Line 3");
        }
    }

    Output

    Line 1
    Line 3

    The second output statement is ignored because it has been commented out.

    Good Comments vs Poor Comments

    A good comment explains why something is done. A poor comment simply repeats what the code already says.

    Poor Comments

    • Repeat obvious code.
    • Are too long without reason.
    • Are outdated or incorrect.
    • Make simple code look complicated.
    • Explain what is already clear from variable names.

    Good Comments

    • Explain the purpose of logic.
    • Clarify complex calculations.
    • Document important decisions.
    • Help future developers understand the code.
    • Stay short, clear, and accurate.

    Poor Comment Example

    // Add number1 and number2.
    int sum = number1 + number2;

    This comment is not very useful because the code is already easy to understand.

    Better Comment Example

    // Apply extra marks before final result calculation.
    totalMarks = totalMarks + bonusMarks;

    This comment is more useful because it explains why the value is being updated.

    Best Practices for Writing Comments

    Comments should be helpful, clear, and professional. Too many unnecessary comments can make code messy.

    Recommended Practices

    • Use comments to explain why code exists.
    • Keep comments short and meaningful.
    • Write comments in simple language.
    • Update comments when code changes.
    • Avoid writing comments for every obvious line.
    • Use single-line comments for short notes.
    • Use multi-line comments for longer explanations.
    • Use documentation comments for classes and methods.
    • Place comments close to the code they explain.
    • Follow consistent formatting style.

    Professional Comment Formatting

    A professional comment should be easy to read and consistent with coding standards.

    Formatting Tips

    • Place important comments on a separate line.
    • Start comment text with a capital letter.
    • End complete comment sentences with a period.
    • Use one space after the comment symbol.
    • Keep comments aligned with the related code.

    Good Formatting

    // Calculate the final amount.
    int finalAmount = price * quantity;

    Poor Formatting

    //calculate final amount
    int finalAmount = price * quantity;

    Complete Java Example Using Comments

    The following program uses different types of comments.

    /**
     * This program calculates the total and average marks of a student.
     */
    public class StudentResult {
        public static void main(String[] args) {
            // Store student name.
            String studentName = "Ravi";
    
            // Store marks of three subjects.
            int mathMarks = 80;
            int scienceMarks = 75;
            int englishMarks = 85;
    
            /*
            Calculate total marks and average marks.
            These values will be displayed as final output.
            */
            int totalMarks = mathMarks + scienceMarks + englishMarks;
            int averageMarks = totalMarks / 3;
    
            // Display final result.
            System.out.println("Student Name: " + studentName);
            System.out.println("Total Marks: " + totalMarks);
            System.out.println("Average Marks: " + averageMarks);
        }
    }

    Output

    Student Name: Ravi
    Total Marks: 240
    Average Marks: 80

    Common Beginner Mistakes

    Mistakes

    • Writing too many unnecessary comments.
    • Not updating comments after changing code.
    • Writing comments that repeat obvious code.
    • Using multi-line comments incorrectly.
    • Forgetting to close a multi-line comment.
    • Using comments instead of writing clear code.
    • Leaving old commented-out code in final programs.
    • Writing confusing or incomplete comments.

    Better Habits

    • Write comments only where helpful.
    • Keep comments accurate and updated.
    • Use meaningful variable and method names first.
    • Use comments to explain complex logic.
    • Close multi-line comments properly.
    • Use documentation comments for important methods.
    • Remove unnecessary commented-out code.
    • Write comments for future readers, not only for yourself.

    Prerequisites Before Learning Comments

    To understand comments properly, students should know some basic programming concepts.

    Basic Prerequisites

    • Basic understanding of programming.
    • Basic program structure.
    • Statements in programming.
    • Expressions in programming.
    • Keywords and identifiers.
    • Variables and data types.
    • Simple Java syntax.
    • Basic understanding of classes and methods.

    Practice Activity: Add Comments

    This activity helps students practice writing useful comments in Java code.

    Task

    Add meaningful comments to the following Java program.
    public class ProductBill {
        public static void main(String[] args) {
            int price = 100;
            int quantity = 3;
    
            int totalAmount = price * quantity;
    
            System.out.println("Total Amount: " + totalAmount);
        }
    }

    Sample Answer

    public class ProductBill {
        public static void main(String[] args) {
            // Store product price.
            int price = 100;
    
            // Store product quantity.
            int quantity = 3;
    
            // Calculate total bill amount.
            int totalAmount = price * quantity;
    
            // Display total amount.
            System.out.println("Total Amount: " + totalAmount);
        }
    }

    Mini Quiz

    1

    What is a comment?

    A comment is a note written inside code to explain the program. It is ignored by the compiler.

    2

    Which symbol is used for single-line comments in Java?

    Single-line comments in Java use //.

    3

    Which symbols are used for multi-line comments?

    Multi-line comments start with /* and end with */.

    4

    What is a documentation comment?

    A documentation comment is a special comment used to document classes, methods, and APIs. It starts with /** and ends with */.

    5

    Do comments affect program output?

    No. Comments are ignored by the compiler, so they do not affect program output.

    Interview Questions on Comments

    1

    Define comments in programming.

    Comments are non-executable notes written in source code to explain logic, improve readability, and help maintain the program.

    2

    What are the types of comments in Java?

    Java supports single-line comments, multi-line comments, and documentation comments.

    3

    Why are comments useful?

    Comments are useful because they explain code, improve readability, support debugging, and help future maintenance.

    4

    What is the difference between single-line and multi-line comments?

    Single-line comments explain one line or short logic, while multi-line comments are used for longer explanations across multiple lines.

    5

    What is Javadoc?

    Javadoc is a documentation style in Java that uses documentation comments to describe classes, methods, parameters, and return values.

    Quick Summary

    Concept Meaning
    Comment A human-readable note written inside code.
    Single-Line Comment Starts with // and continues to the end of the line.
    Multi-Line Comment Starts with /* and ends with */.
    Documentation Comment Starts with /** and is used for Javadoc documentation.
    Commenting Out Temporarily disabling code using comments.
    Good Comment Explains why code exists or clarifies complex logic.
    Poor Comment Repeats obvious code or becomes outdated.

    Final Takeaway

    Comments are an important part of writing clean and understandable programs. They do not execute, but they help humans understand the code. Students should use comments to explain important logic, document methods and classes, support debugging, and make programs easier to maintain. Good comments are clear, short, accurate, and helpful.