Java Reference
In-Depth Information
Java syntax: Variable declaration
type
variable
;
Java syntax: Assignment statement
variable
=
expression
;
Example
:
double
price
;
Additionally:
The type of the
variable
is the same as
or wider than the type of the
expression
.
Purpose
: To declare that variable
variable
is needed and that it can hold values of type
type
. By
variable
, we mean the name of the
variable.
Example
:
price= 8.99
;
Purpose
: To assign a value to a variable. To execute
the assignment, evaluate the
expression
and store its
value in the
variable
.
variable before the assignment is performed.
//
legal:
double
is wider than
int
price= 4;
//
illegal:
int
is narrower than
double
quantity= 5.0;
Expressions with variables
We can write expressions not only with literals (for example,
4
,
6.2
, and
true
), but with variables. Here is one such expression:
price + 4.0
. When an
expression with a variable is evaluated, the value currently associated with the
variable is used. For example, if
quantity
has the value
8
and
price
has the
value
3.99
, the value of the expression
quantity * price
is
31.92
. If the value of a variable changes, later evaluation of the same expres-
sion yields a different value.
Below, we show a sequence of assignments to
int
variables
v1
and
v2
. As
each assignment is executed, one after the other, the new values of the variables
are as shown in the comments to the right of the assignment. The values are the
numbers that appear after the colons.
v1= 5; // v1: 5 v2: ?
v2= 3; // v1: 5 v2: 3
v1= v1 + 1; // v1: 6 v2: 3
v1= v1 + 2 + v1; // v1: 14 v2: 3
v2= v1; // v1: 14 v2: 14
v1= v2 + v1 + 1; // v1: 29 v2: 14
In mathematics, short variable names like
x
and
y
are common. In comput-
er programs, longer names tend to be used in order to give some indication of
their meaning, like
price
and
taxIsIncluded
. There is a tension between using
short names, in order to keep a program compact, and long names, in order to
provide more understanding. Our conventions for names are discussed in Sec.
13.1, and we recommend that you read the beginning of that section now.
The following convention is followed by Java programmers: a variable
Lesson page
13-2 discusses
naming con-
ventions in
detail.
Search WWH ::
Custom Search