Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 65

Comments

Оглавление

Another common part of the code is called a comment. Because comments aren't executable code, you can place them in many places. Comments can make your code easier to read. While the exam creators are trying to make the code harder to read, they still use comments to call attention to line numbers. We hope you use comments in your own code. There are three types of comments in Java. The first is called a single-line comment:

// comment until end of line

A single-line comment begins with two slashes. The compiler ignores anything you type after that on the same line. Next comes the multiple-line comment:

/* Multiple * 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 probably 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 the following six words is in? Is it a single-line or a multiline comment?

/* * // anteater */ // bear // // 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 looking at code carefully.

Okay, on to the answers. The comment containing 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! The comment containing bear is your basic single-line comment. The comments containing 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. The comment containing elephant is your basic multiline comment, even though it only takes up one line.

The line with ferret is interesting in that it doesn't compile. Everything from the first /* to the first */ 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.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх