Another common part of the code is called a comment. Because comments aren’t executable code, you can place them anywhere. Comments make your code easier to read. You won’t see many comments on the exam—the exam creators are trying to make the code difficult to read—but you’ll see them in this book as we explain the code. And we hope you use them in your own code. There are three types of comments in Java. The fi rst is called a single-line comment:
// comment until end of line
A single-line comment begins with two slashes. Anything you type after that on the same line is ignored by the compiler. Next comes the multiple-line comment:
* line comment
A multiple-line comment (also known as a multiline comment) includes anything starting from the symbol /* until the symbol */. People often type an asterisk (*) at the beginning of each line of a multiline comment to make it easier to read, but you don’t have to. Finally, we have a Javadoc comment:
* Javadoc multiple-line comment
* @author Jeanne and Scott
This comment is similar to a multiline comment except it starts with /**. This special syntax tells the Javadoc tool to pay attention to the comment. Javadoc comments have a specific structure that the Javadoc tool knows how to read. You won’t see a Javadoc comment on the exam—just remember it exists so you can read up on it online when you start writing programs for others to use.
As a bit of practice, can you identify which type of comment each of these fi ve words is in? Is it a single-line or a multiline comment?
* // anteater
// // cat
// /* dog */
/* elephant */
* /* ferret */
Did you look closely? Some of these are tricky. Even though comments technically aren’t on the exam, it is good to practice to look at code carefully.
Okay, on to the answers. anteater is in a multiline comment. Everything between /* and */ is part of a multiline comment—even if it includes a single-line comment within it! bear is your basic single-line comment. cat and dog are also single-line comments. Everything from // to the end of the line is part of the comment, even if it is another type of comment. elephant is your basic multiline comment. The line with ferret is interesting in that it doesn’t compile. Everything from the fi rst /* to the fi rst */ is part of the comment, which means the compiler sees something like this:
/* */ */
We have a problem. There is an extra */. That’s not valid syntax—a fact the compiler is
happy to inform you about.