Java Reference
In-Depth Information
Just about every loop in this text is accompanied by a loop invariant that helps
one understand the loop, and we encourage you to annotate your loops with
invariants as well.
As the example above shows, a loop invariant is written as a comment just
before the loop and is indented exactly the same amount as the loop. It has the
identifying prefix “
invariant:
” or “
inv:
”.
13.2.4
Indenting the body of a method
We place the opening brace of the body of a method after the header, we indent
the statements of the body 4 spaces, and we place the closing brace on a separate
line, beginning in the same column as the header of the method:
/**
Print
x
,
y
, and
z,
titled, each on a separate line.
*/
public static void
printxyz(
int
x,
int
y,
int
z) {
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
}
Note that the specification of the method appears above the header, and the
specification and method begin in the same column.
13.2.5
Indenting components of a class
It is common practice to indent all fields and methods of a class 4 spaces, as
shown in Fig. 13.2. The opening brace
{
of the class body is on the same line as
the class name and the closing brace is in the same column as the first word of
the class definition.
public class
Example {
public static final
int PI= 3.1459;
private int
field;
/**
Constructor: an instance with
field = f */
public
Example(
int
f) {
field= f;
}
/** =
a
String
representation of this instance
*/
public
String toString() {
return
" " + field;
}
}
Figure 13.2:
Example of indentation of components of a class
Search WWH ::
Custom Search