There was an error in this gadget

Wednesday, June 18, 2008

Comments

Comments are lines of the program that are just for humans to read. The computer ignores them. They're useful for putting in notes about what the program is doing, who wrote it and when, and so on.

Here's a program that includes some comments. One way of putting a comment in a Java program is in red, the other way is in green:

/* Hello.java
  A really simple program that prints the word hello.
  This program is a console, or command-line program.
*/
// Written 18 June 2008

public class Hello{
  public static void main(String arg[]){
    System.out.println("Hello");
  } // End of main()
} // End of Hello
The /* marks the start of the first comment. The compiler sees the /* and ignores everything it sees until it gets to the */. Other text could have been on the same line as the */, it doesn't have to be on its own line. The compiler would ignore any text that appears before the */, and read anything that comes after.

A comment that starts with a /* and ends with a */ is called a multi-line comment. It can go across multiple lines easily. It can all be on one line, though--it doesn't have to be split across multiple lines:

/* This is a perfectly OK comment. */

The second type of comment starts with a //. When the compiler sees a // it ignores everything that follows up until the end of that line. As soon as it reaches the end of the line, it starts reading again.

In the example program, I've got a line with the date the program was written that uses the //, and I've used it at the closing curly braces for each block in the program to add comments there about which program block is being closed.

Just to make sure I'm clear here, I want to point out that there's nothing magic about what's in these comments. They don't affect the program. The comment that reads // End of main() could just as well read // Arfn Snuglhoffer. The computer doesn't care. I just wrote "End of main()" to let me know that the closing curly brace the comment is next to closes the main() method of Hello, so I don't get it confused with any other closing curly braces.
StumbleUpon