Java Reference
In-Depth Information
public StaticBlockClass(int identifier) {
whichOne = Integer.toString(identifier);
}
public StaticBlockClass(String identifier) {
whichOne = identifier;
}
}
As you can see, the field we set also has to be static. However, because we don't want to change it,
that's just fine. In this case, we don't gain much by having a static block. However, imagine if we have
ten values to set and four constructors.
Aside from saving space (though not in this example), the real value of static blocks makes sure that
everything the class needs gets into each constructor. You can get bugs from having things set in some
constructors but not others, and static blocks can help you manage that problem.
Comments
Comments are lines of code that are (usually) meant purely for humans to read. The compiler utterly
ignores comments. Java supports two styles of comments, end-of-line comments and block comments.
The code examples I provide have many end-of-line comments. End-of-line comments begin with two
slash characters ( // ), thus:
// end-of-line comment that happens to be the only thing on the line
End-of-line comments can also start after other code on the line, thus:
int counter = 0; // Initialize the counter
Code cannot follow an end-of-line comment on the same line. It would become part of the
comment.
Block comments begin with a slash and an asterisk ( /* ) and end with an asterisk and a slash ( */ ).
Block comments can be on one line, but they can also consist of multiple lines. Block comments can
start on the same line as other code. In fact, block comments can occur between code elements on the
same line (possibly making the line of code consist of multiple lines in the file). As ever, examples help.
Here's a block comment by itself on a single line:
/* comment */
And here's a line of code with a comment in the middle of it:
int counter /* comment */ = 0;
Please don't do that. It's legal, but it's poor coding practice, because it makes the code harder to
read.
Now let's look at multi-line block comments in Listing 2-18.
Listing 2-18. Multi-line block comment
/* Now is the time for all good coders to write meaningful comments,
so that the rest of us can understand what the code is doing. */
Listing 2-19 shows another multi-line block comment, mingled with code.
Search WWH ::




Custom Search