Comments

From CompSciWiki
Revision as of 22:35, 7 December 2011 by JordanW (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

COMP 1010 Home > Java Fundamentals


Introduction

A comment is text you add to your source code to help make it easer to read, explain why you did something or some other documentation such as your professor asking for a header at the top of each file. Comments can be written anywhere in your program and will not cause problems when you go to run your program.

Types of Comments

Inline Comments

 int max_gpa = 4.5;  // Declare a variable for the maximum gpa 

An inline comment allows comments to be added to a single line of code. Everything after the // is ignored when the program is run.

Block Comments

 /*******************************************************************************
 * PrintTemp
 *
 * This program shows you how to print the contents of a variable
 *
 * COMP 1010
 * Instructor:   Compsci Wiki
 * Assignment:   Assignment 0, question 0
 * @author       Compsci Wiki
 * @version      
 ***********************************************************************************/ 

A block comment is for multiline use. You begin a block comment with /* and everything after until you reach a */ is the comment. This is what you will normally see for file and method headers. As you can see in the example below, extra *'s can be used to give better separation to the comment.


Example of a Java Program with Comments

 /*******************************************************************************
 * PrintTemp
 *
 * This program shows you how to print the contents of a variable
 *
 * COMP 1010
 * Instructor:   Compsci Wiki
 * Assignment:   Assignment 0, question 0
 * @author       Compsci Wiki
 * @version      
 ***********************************************************************************/

public class PrintTemp
{
    public static void main(String args[]) 
    {
        int temp; //declare an variable of type integer
        temp = 25; //store 25 in a variable

        //print the temperature to the screen
        System.out.println("The temperature is currently " + temp + " degrees Celsius."); 
    }
} 

Warning 24.pngWARNING

Comments make your code easier to read for everyone, including professors and their markers. Take a lesson from a former student: you will lose marks from your assignments if you do not document your code.


Summary

The two types of comments, block and inline, help to document your code. This documentation makes code easier to understand and maintain. In the next section you will start to learn how to make programs interactive by writing text to the monitor using System.out.

Previous Page: What is Programming? Next Page: Output using System.out.