Page 92 - Introduction to Programming with Java: A Problem Solving Approach
P. 92
58 Chapter 3 Java Basics
/******************************************
*
Dream.java
Dean & Dean
⎫ ⎢ ⎬ ⎢
*
Comments for human readers.
*
This program prints "I have a dream." ⎭ ******************************************/
*
public class Dream ⎫
{
⎢
⎢ {⎬
public static void main(String[] args)
System.out.println("I have a dream!"); ⎢ ⎢
}
// end class Dream
⎭
Instructions for the computer to execute.
}
Comment for human readers.
Figure 3.1 Dream program
3.3 Comments and Readability
Apago PDF Enhancer
In the real world, you’ll spend a lot of your time looking at and fixing other people’s code. And other people will spend a lot of their time looking at and fixing your code after you’ve moved on to something else. With all this looking at other people’s code going on, everyone’s code needs to be understandable. One key to un- derstanding is good comments. Comments are words that humans read but the compiler 2 ignores.
One-Line-Comment Syntax
There are two types of comments—one-line comments and block comments. If your comment text is short enough to fit on one line, use a one-line comment. One-line comments start with two slashes. Here’s an example:
} // end class Dream
The compiler ignores everything from the first slash to the end of the line. So in the above line, the compiler pays attention only to the right brace (}) and ignores the rest of the line. Why is the comment helpful? If you’re viewing a long piece of code on a computer screen and you’ve scrolled to the bottom of the code, it’s
nice to see a description of the code (e.g., end up to the beginning of the code.
Block-Comment Syntax
class
Dream) without having to scroll all the way back
If your comment text is too long to fit on one line, you can use multiple one-line comments, but it’s a bit of a pain to retype the //’s for every line. As an alternative, you can use a block comment. Block comments start with an opening /* and end with a closing */. Here’s an example:
2 A compiler, defined in Chapter 1, is a special program that converts a source-code program into an executable program. An execut- able program is a program that the computer can execute directly.