Java Reference
In-Depth Information
Note that the char data type is a primitive and is restricted to storing a single
character. When programmers want to store more than one character, they often
use the non-primitive String class, which can store more than a single character.
Classes such as String, Date (which you accessed in Chapter 2), and arrays
(which you will learn about in a later chapter) are considered reference data
types or object types. A reference data type is a data type whose value is an
address. Like a primitive data type, a reference data type is declared with an
identifier name, but that identifier references the location of the data rather than
the actual data.
Declaring Variables
A declaration statement is a line of Java code that identifies, or declares,
the data type and names the identifier or variable. Programmers also can use the
declaration statement to assign an initial value or call a constructor method to
declare an instance of a class as they declare their variables. Table 3-3 shows the
general form of declaration statements.
Table 3-3
Declaration Statements
General form:
1. dataType identifier; //simple declaration
2. dataType identifier, identifier, identifier; //multiple declarations
3. dataType identifier = initialValue; //declaration and initialization
4. dataType identifier = new constructorMethod(); //declaration
and construction
Purpose:
To allocate a storage location and specify the type of data or
object it will hold.
Examples:
1.int userAge;
2.boolean flag, done, membership;
3.double taxRate = .05;
4.Date currentDate = new Date();
Figure 3-9 displays the declaration statements that declare the variables used
in the Body Mass Index Calculator program. If you want to declare variables
with different data types, you must use a separate declaration statement for each
data type. If, however, you have several variables of the same data type, you can
list the data type once and then include each variable on the same line separated
by commas, as shown in lines 18 and 19 in Figure 3-9. You must declare a vari-
able before you can use it in a program; however, you can combine the declara-
tion of a variable with its first value or assignment, as shown in example 3 in
Table 3-3.
16
// declare and construct variables
17
String height, weight;
18
int inches, pounds;
19
double kilograms, meters, index;
FIGURE 3-9
 
Search WWH ::




Custom Search