Here are several examples of variable declarations of various types. Note that some
include an initialization.
int a, b, c;
//
declares three ints, a, b, and c.
int d = 3, e, f = 5;
//
declares three more ints, initializing
//
d and f.
byte z = 22;
//
initializes z.
double pi = 3.14159;
//
declares an approximation of pi.
char x = 'x';
//
the variable x has the value 'x'.
The identifiers that you choose have nothing intrinsic in their names that indicates their
type. Java allows any properly formed identifier to have any declared type.
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows variables
to be initialized dynamically, using any expression valid at the time the variable is declared.
For example, here is a short program that computes the length of the hypotenuse of
a right triangle given the lengths of its two opposing sides:
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Here, three local variables--a, b, and c--are declared. The first two, a and b, are initialized
by constants. However, c is initialized dynamically to the length of the hypotenuse (using
the Pythagorean theorem). The program uses another of Java's built-in methods, sqrt( ), which
is a member of the Math class, to compute the square root of its argument. The key point here is
that the initialization expression may use any element valid at the time of the initialization,
including calls to methods, other variables, or literals.
The Scope and Lifetime of Variables
So far, all of the variables used have been declared at the start of the main( ) method. However,
Java allows variables to be declared within any block. As explained in Chapter 2, a block is
begun with an opening curly brace and ended by a closing curly brace. A block defines a
scope. Thus, each time you start a new block, you are creating a new scope. A scope determines
what objects are visible to other parts of your program. It also determines the lifetime of
those objects.
Many other computer languages define two general categories of scopes: global and local.
However, these traditional scopes do not fit well with Java's strict, object-oriented model.
While it is possible to create what amounts to being a global scope, it is by far the exception,
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home