Java Reference
In-Depth Information
the program in Listing 2.2,
radius
and
area
are variables of the double-precision, floating-
point type. You can assign any numerical value to
radius
and
area
, and the values of
radius
and
area
can be reassigned. For example, in the following code,
radius
is initially
1.0
(line 2) and then changed to
2.0
(line 7), and area is set to
3.14159
(line 3) and then
reset to
12.56636
(line 8).
1
// Compute the first area
2 radius =
1.0
; radius: 1.0
3 area = radius * radius *
3.14159
; area: 3.14159
4 System.out.println(
"The area is "
+ area +
"
for
radius "
+ radius);
5
6
// Compute the second area
7 radius =
2.0
; radius: 2.0
8 area = radius * radius *
3.14159
; area: 12.56636
9 System.out.println(
"The area is "
+ area +
"
for
radius "
+ radius);
Variables are for representing data of a certain type. To use a variable, you declare it by
telling the compiler its name as well as what type of data it can store. The
variable declara-
tion
tells the compiler to allocate appropriate memory space for the variable based on its data
type. The syntax for declaring a variable is
datatype variableName;
Here are some examples of variable declarations:
declare variable
int
count;
// Declare count to be an integer variable
double
radius;
// Declare radius to be a double variable
double
interestRate;
// Declare interestRate to be a double variable
These examples use the data types
int
and
double
. Later you will be introduced to addi-
tional data types, such as
byte
,
short
,
long
,
float
,
char
, and
boolean
.
If variables are of the same type, they can be declared together, as follows:
datatype variable1, variable2, ..., variablen;
The variables are separated by commas. For example,
int
i, j, k;
// Declare i, j, and k as int variables
Variables often have initial values. You can declare a variable and initialize it in one step.
Consider, for instance, the following code:
initialize variables
int
count =
1
;
This is equivalent to the next two statements:
int
count;
count =
1
;
You can also use a shorthand form to declare and initialize variables of the same type
together. For example,
int
i =
1
, j =
2
;
Tip
A variable must be declared before it can be assigned a value. A variable declared in a
method must be assigned a value before it can be used.
Whenever possible, declare a variable and assign its initial value in one step. This will
make the program easy to read and avoid programming errors.