Java Reference
In-Depth Information
Sticking with the Java naming conventions makes your programs easy to read and
avoids errors.
Key
Point
Make sure that you choose descriptive names with straightforward meanings for the variables,
constants, classes, and methods in your program. As mentioned earlier, names are case sensi-
tive. Listed below are the conventions for naming variables, methods, and classes.
Use lowercase for variables and methods. If a name consists of several words, con-
catenate them into one, making the first word lowercase and capitalizing the first
letter of each subsequent word—for example, the variables
radius
and
area
and
the method
print
.
name variables and methods
■
Capitalize the first letter of each word in a class name—for example, the class names
ComputeArea
and
System
.
name classes
■
Capitalize every letter in a constant, and use underscores between words—for exam-
ple, the constants
PI
and
MAX_VALUE
.
name constants
■
It is important to follow the naming conventions to make your programs easy to read.
Caution
Do not choose class names that are already used in the Java library. For example, since
the
System
class is defined in Java, you should not name your class
System
.
name classes
2.7
What are the benefits of using constants? Declare an
int
constant
SIZE
with value
20
.
2.8
What are the naming conventions for class names, method names, constants, and
variables? Which of the following items can be a constant, a method, a variable, or a
class according to the Java naming conventions?
MAX_VALUE
,
Test
,
read
,
readDouble
2.9
Translate the following algorithm into Java code:
Step 1: Declare a
double
variable named
miles
with initial value
100
.
Step 2: Declare a
double
constant named
KILOMETERS_PER_MILE
with value
1.609
.
Step 3: Declare a
double
variable named
kilometers
, multiply
miles
and
KILOMETERS_PER_MILE
, and assign the result to
kilometers
.
Step 4: Display
kilometers
to the console.
✓
✓
Check
Point
What is
kilometers
after Step 4?
Java has six numeric types for integers and floating-point numbers with operators
+
,
-
,
*
,
/
, and
%
.
Key
Point
2.9.1 Numeric Types
Every data type has a range of values. The compiler allocates memory space for each var-
iable or constant according to its data type. Java provides eight primitive data types for
numeric values, characters, and Boolean values. This section introduces numeric data types
and operators.
Table 2.1 lists the six numeric data types, their ranges, and their storage sizes.
Search WWH ::
Custom Search