Java Reference
In-Depth Information
✓
✓
2.2
How do you write a statement to let the user enter an integer or a double value from
the keyboard?
Check
Point
2.3
What happens if you entered
5a
when executing the following code?
double
radius = input.nextDouble();
Identifiers are the names that identify the elements such as classes, methods, and
variables in a program.
Key
Point
As you see in Listing 2.3,
ComputeAverage
,
main
,
input
,
number1
,
number2
,
number3
,
and so on are the names of things that appear in the program. In programming terminology,
such names are called
identifiers.
All identifiers must obey the following rules:
identifiers
identifier naming rules
An identifier is a sequence of characters that consists of letters, digits, underscores
(
_
), and dollar signs (
$
).
■
An identifier must start with a letter, an underscore (
_
), or a dollar sign (
$
). It cannot
start with a digit.
■
An identifier cannot be a reserved word. (See Appendix A for a list of reserved words.)
■
An identifier cannot be
true
,
false
, or
null
.
■
An identifier can be of any length.
■
For example,
$2
,
ComputeArea
,
area
,
radius
, and
showMessageDialog
are legal
identifiers, whereas
2A
and
d+4
are not because they do not follow the rules. The Java com-
piler detects illegal identifiers and reports syntax errors.
Note
Since Java is case sensitive,
area
,
Area
, and
AREA
are all different identifiers.
case sensitive
Tip
Identifiers are for naming variables, constants, methods, classes, and packages. Descrip-
tive identifiers make programs easy to read. Avoid using abbreviations for identifiers.
Using complete words is more descriptive. For example,
numberOfStudents
is better
than
numStuds
,
numOfStuds
, or
numOfStudents
. We use descriptive names for
complete programs in the text. However, we will occasionally use variables names such
as
i
,
j
,
k
,
x
, and
y
in the code snippets for brevity. These names also provide a generic
tone to the code snippets.
descriptive names
Tip
Do not name identifiers with the
$
character. By convention, the
$
character should be
used only in mechanically generated source code.
the
$
character
✓
✓
2.4
Which of the following identifiers are valid? Which are Java keywords?
miles
,
Test
,
a++
,
--a
,
4#R
,
$4
,
#44
,
apps
class
,
public
,
int
,
x
,
y
,
radius
Check
Point
Variables are used to represent values that may be changed in the program.
Key
Point
As you see from the programs in the preceding sections, variables are used to store values to
be used later in a program. They are called variables because their values can be changed. In
why called variables?