Java Reference
In-Depth Information
Java syntax: local variable declaration
type variable ;
Example : int temperature;
Purpose : Introduce a variable that can be
used in the sequence of statements that fol-
lows the declaration.
Java syntax: initializing declaration
type variable-name = expression ;
Example : int temperature= 50;
Purpose : Introduce a variable that can be used
in the sequence of statements that follows the
declaration and give it an initial value.
type variable-name= expression ;
Style Note
13.1.1:
local-variable
names
Method drawTriangle of Fig. 2.4 draws a triangle in a graphics window g .
Its body is not as easy to understand as it could be because of the many expres-
sions, some of which are duplicated. For example, the expression y+h appears
four times. Not only does this complicate the body, it is inefficient. We can make
the body clearer and more efficient by using local variables.
Figure. 2.5 shows the same procedure as in Fig. 2.4, but with three local
variables. While their declarations and initializations make the procedure look
longer, the statements that do the work (the three calls to procedure drawLine )
are easier to understand.
Note the use of a comment to describe what a local variable is being used
for. The comment mentions not only the local variable but other variables as
well. Variables are related to each other, and one often describes them together.
Quite often, a declaration of a variable is followed by an assignment that
provides the variable with its initial value. It is possible —and usually advanta-
geous— to combine the two into a single initializing declaration . For example,
the three local variables in Fig. 2.5 were declared and initialized using these three
initializing declarations:
Style Note
13.4:
describing
variables
Activity
2-3.2
// (x, y1) is the left lower vertex
int y= y + h;
// (x1, y1) is the right lower vertex
int x1= x + w;
// (x2, y) is the top vertex
int x2= x +w/2;
A variable can be declared only once, but it can be assigned many times. In
/** Using g , draw a triangle that fits in the rectangle drawn by drawRect(x, y, w, h) .
One side is the base of the rectangle; the other two sides meet at pixel (x + w / 2, y) . */
public void drawTriangle(Graphics g, int x, int y, int w, int h) {
int y1= y + h; // (x, y1) is the left lower vertex
int x1= x + w; // (x1, y1) is the right lower vertex
int x2= x + w / 2; // (x2, y) is the top vertex
g.drawLine(x, y1, x1, y1);
g.drawLine(x, y1, x2, y);
g.drawLine(x1, y1, x2, y);
}
Figure 2.5:
Drawing a triangle using local variables
Search WWH ::




Custom Search