Comments

From CompSciWiki
Revision as of 15:00, 16 September 2010 by WikiSysop (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > Java Fundamentals


Introduction

When a program is compiled, the compiler ignores the comments. This means that comments do not affect the program. So, why do we use comments? Comments are only for you and any one else that reads your source code. To see the value of comments, imagine someone gives you the source code to a long, complex program which does not contain any comments. If you wanted to understand the code you would have to spend a lot of time going through each line and figuring out what everything does. However, if this program had comments that explained the purpose of each class, method, and block of code, it would make understanding the code a lot easier.

Example of a Java Program with Comments

Take a look at the example below. You will notice that some of the text does not look like Java code - they are normal English sentences. Since Java will not understand these sentences, we use certain characters to denote that sections of text are comments.

If you want to write a comment that is longer than one line, put /* at the beginning of the comment and */ at the end. In COMP 1010 you'll have to put a multi-line comment at the start of all assignment programs. Do this or they'll take off marks!

You'll also have to (and actually want to) add comments to remind yourself, and anyone else who reads your program, about the various parts of your program. If the comment is only one line long, use //. The text that appears after // is a comment.

/*******************************************************************************
 * 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

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

To review, you should add comments to your programs (also called source code) to improve organization and to help someone else understand what your code does.

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