Java Reference
In-Depth Information
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 print are legal identifiers, whereas
2A and d+4 are not because they do not follow the rules. The Java compiler 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, methods, classes, and other items in a program.
Descriptive identifiers make programs easy to read. Avoid using abbreviations for identi-
fiers. 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 variable
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
2.5 Variables
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 the program in Listing 2.2, radius and area are variables of the double 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).
why called variables?
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 declaration
 
 
 
Search WWH ::




Custom Search