Java Reference
In-Depth Information
Variables
Every variable in a Java program must be declared before it is used. When you
declare
a variable, you are telling the compiler—and, ultimately, the computer—what kind of
data you will be storing in the variable. For example, the following are two declarations
that might occur in a Java program:
declare
int
numberOfBeans;
double
oneWeight, totalWeight;
The first declares the variable
numberOfBeans
so that it can hold a value of type
int
;
that is, a whole number. The name
int
is an abbreviation for “integer.” The type
int
is the default type for whole numbers. The second definition declares
oneWeight
and
totalWeight
to be variables of type
double
, which is the default type for numbers
with a decimal point (known as
floating-point numbers
). As illustrated here, when
there is more than one variable in a declaration, the variables are separated by commas.
Also, note that each declaration ends with a semicolon.
Every variable must be declared before it is used. A variable may be declared anyplace,
so long as it is declared before it is used. Of course, variables should always be declared in
a location that makes the program easier to read. Typically, variables are declared either
just before they are used or at the start of a block (indicated by an opening brace
{
). Any
legal identifier, other than a keyword, may be used for a variable name.
floating-point
number
Variable Declarations
In Java, a variable must be declared before it is used. Variables are declared as described here.
SYNTAX
Type Variable_1
,
Variable_2,. . .;
EXAMPLES
int
count, numberOfDragons, numberOfTrolls;
char
answer;
double
speed, distance;
Syntactic Variables
Remember that when you see something such as
Type
,
Variable_1
, or
Variable_2
, these
words do not literally appear in your Java code. They are
syntactic variables
, which means
they are replaced by something of the category that they describe. For example,
Type
can
be replaced by
int
,
double
,
char
, or any other type name.
Variable_1
and
Variable_2
can
each be replaced by any variable name.