Variables
A Java program manipulates values, represented in source code by literals. Those values are typically stored in memory locations, with each memory location represented by a name and a type at the source code level. The combination of name and type is known as a variable.
Java classifies a variable in three ways. First, that variable is either a primitive variable (based on a primitive type) or a reference variable (based on a reference type). Second, that variable is either a simple variable (capable of storing a single value) or an array variable (capable of storing multiple values). Finally, that variable is either a class variable, an instance variable, an array component variable, a method parameter variable, a constructor parameter variable, an exception handler parameter variable, or a local variable.
With so much to learn, it's easy to feel overwhelmed. Therefore, to make variables easier to understand, this section examines only a few conceptsthe declaration and initialization of primitive and reference array and non-array variables, to be exact. Later chapters cover the remaining concepts.
Declaration
Variables must be declared before they can be used. A variable declaration introduces a variable to the compiler as a name and a type. The way the variable is declared depends on whether it is a simple variable or an array variable.
Simple Variable Declaration
A simple variable is declared by using the following syntax:
typeIdentifier variableIdentifier ';'According to the syntax, typeIdentifier specifies the variable's type using either a primitive type keywordboolean, byte, char, double, float, int, long, or shortor a reference type identifier (such as String). The name of the variable is specified by variableIdentifier and must not be a reserved word.
The following declarations introduce a few simple variables of primitive and reference types:
int \u3063; | \u3063 (Hiragana letter) stores an integer. |
double amountOwing; | amountOwing stores a double-precision floating-point number. |
String lastName; | lastName stores a reference to a String object. |
Caution
Reserved words cannot be used as variable names. For example, the compiler flags int while; as an error because while is a reserved word.
Multiple simple variables can be specified in a single variable declaration by separating the variable names with commas.
The following declaration introduces a few simple variables of primitive type integer:
int count, total, age;Array Variable Declaration
An array variable is declared by using the following syntax:
typeIdentifier '[' ']' variableIdentifier ';'The array variable declaration syntax is similar to the previous simple variable declaration syntax. As with simple variable declarations, variableIdentifier names the array variable and must not be a reserved word. However, typeidentifier is a little different in the context of arrays.
Before continuing, ask yourself the following question: What is an array? The answer is: a block of memory divided into separate storage locations. Each storage location is capable of holding a single value of a specific type. However, the types of all values in all of those storage locations must be the same. And what is that type? The answer is: typeIdentifier.
Java regards an array as an object. variableIdentifier contains a reference to a block of memory. Each of the storage locations in that block is known as an array component variable or element and is identified by an index. typeIdentifier is the type of each element and is represented in source code either by a primitive type keywordboolean, byte, char, double, float, int, long, or shortor by a reference type identifier (such as String). In contrast, typeIdentifier [] represents the type of variableIdentifier (and is a reference type).
The following declarations introduce a few array variables whose elements are of primitive and reference types:
char [] gradeLetters; |
gradeLetters references an array of characters. |
float [] temps; |
temps references an array of floating- point numbers. |
String [] countryNames; |
countryNames references an array of references to String objects. |
The example declares three array variables. The gradeLetters array is of type character [] (as represented by char []), and the type of each element is character. Similarly, the temps array is of type floating-point [] (as represented by float []), and the type of each element is floating-point. Finally, the countryNames array is of type String [], and the type of each element is String.
Declaration causes memory to be allocated for array variables but not for the storage locations comprising each array. After all, there is no indication of the size of the array (that is, the number of elements composing the array) during declaration. Later, you will learn how to allocate memory for array elements.
As a concession to C/C++, Java allows you to specify the square brackets after the variable name (as in int inventoryTotals [];). However, to improve source code readability, it is customary to specify the square brackets after typeIdentifier.
Cautions
Unlike in C++, you must not specify the size of the array by placing either an integer literal or an integer variable, initialized to some value, between the square brackets. For example, do not specify char [10] gradeLetters; to declare a gradeLetters array capable of storing 10 characters. Also, do not specify int inventoryTotals [i];where i is an integer variable initialized to some value. Either declaration results in a compiler error message.
Multiple array variables can be specified in a single variable declaration by separating the variable names with commas.
The following declaration introduces a few array variables whose elements are of type String:
String [] names, addresses, cities;Initialization
During declaration, a variable can be initialized to a value. The way the variable is initialized depends on whether it is a simple variable or an array variable.
Simple Variable Initialization
A simple variable can be initialized when it is declared by using the following syntax:
typeIdentifier variableIdentifier [ '=' expression ] ';'To initialize a simple variable as part of its declaration, specify assignment operator = followed by an expression whose type matches typeIdentifier.
The following declarations introduce a few initialized simple variables of primitive and reference types:
int age = 65; double balance = 30000.0; String name = "Sun Microsystems";
In the example, both age and 65 are of type integer. Therefore, the initialization of age to 65 is legal. The other declarations are also legal because the variable and expression types match.
The following declarations are illegal because the types of the variable and expression (in each declaration) do not match:
short s = 50000; int i = "abc";
In the first declaration, an attempt is made to assign an integer literal to a short integer variable, which is unacceptableunless a cast operator is used to implement a narrowing conversion rule. (A corrected version of the first declaration is shown where cast operators are discussed in the Unary Operators section of this chapter.) In the second declaration, an attempt to assign a string literal (of type String) to an integer variable is meaningless, and there is no cast operator to make a correction.
Caution
Attempting to initialize a variable with a literal of a different type is a common source of error. However, Java allows some flexibility in that area: Java supports the assignment of certain integer literals to byte and short integer variables.
The compiler allows only one situation where literals of one type can be assigned to variables of another type: An integer literal can be assigned to either a byte variable, a short integer variable, or a character variable provided that the value of the literal fits within the variable's acceptable range of values.
The following declarations with initialization prove that it is possible to assign integer literals to byte, short integer, or character variables.
byte b = 100; short s = 1000; char c = 60000;
The first declaration is legal because 100 fits within a byte's range of values: -128 to 127 (inclusive). Similarly, the second declaration is legal because 1000 fits within a short integer's -32768 to 32767 (inclusive) range of values. Finally, the third declaration is legal because 60000 fits within a character's range of values: 0 to 65535 (inclusive).
After a simple variable has been initialized, its value can be accessed by specifying the variable's name in source code.
The following code fragment declares and initializes a variable named b1. Then, a variable named b2 is declared and initialized to the value contained in b1.
byte b1 = 100; byte b2 = b1;
Multiple simple variables can be initialized in a single variable declaration by using commas.
The following declaration introduces a few simple variables of primitive type integer and initializes two of those variables:
int count = 0, total, age = 25;To put simple variable declaration and initialization concepts into perspective, Figure 3.2 illustrates the parts of a simple variable declaration and initialization, and the resulting memory representation.
Figure 3.2: A simple variable is declared and initialized, and the result is stored in memory.
Array Variable Initialization
An array variable can be initialized when it is declared by using the following syntax:
typeIdentifier '[' ']' variableIdentifier [ '=' '{' expression ',' ... ',' expression '}' ] ';'
To initialize an array variable when it is declared, specify the assignment operator = followed by a comma-delimited sequence of expressions that are placed between brace characters { and }. Each expression's type must match the type represented in source code by typeIdentifier.
The following declarations introduce a few initialized array variables of primitive and reference types:
char [] yesNo = { 'Y', 'y', 'N', 'n' }; float [] percents = { 0.25f, 0.5f, 0.75f }; String [] titles = { "Dr.", "Mr.", "Mrs.", "Ms.", "Rev." };
yesNo is an array of four character elements; percents is an array of three floating-point elements; and titles is an array of five String reference elements. Notice the lowercase letter f appearing to the right of 0.25, 0.5, and 0.75. That letter specifies each literal's type as floating-point.
After an array variable has been initialized, its values can be accessed by specifying the following syntax:
variableIdentifier '[' expression ']'The syntax shows how to access an array element. expression is an integer expression that indexes (that is, accesses) a specific array element. (A 0 value accesses element 0, a 1 value accesses element 1, and so on.) Like C++, Java's array elements begin at index zero.
The following code fragment declares and initializes an array variable called innerPlanetNames and accesses the second element (at index oneVenus), which subsequently prints:
String [] innerPlanetNames = { 'Mercury', 'Venus', 'Earth', 'Mars' }; System.out.println (innerPlanetNames [1]);
Java provides a convenient mechanism for determining the number of elements in an arraythe length property. To return the length of an array, simply attach a period character followed by length to the array variable's name.
The following code fragment returns the length of the previous example's innerPlanetNames array (which is four) and subsequently prints that value:
System.out.println (innerPlanetNames.length);Multiple array variables can be initialized in a single variable declaration. That is accomplished by using commas to separate variable names from initializations.
The following declaration introduces a few array variables whose elements are of primitive type integer and initializes two of those variables:
int [] num1 = { 1, 2 }, num2, num3 = { 3, 4, 5 };To put the array variable declaration and initialization concepts into perspective, Figure 3.3 illustrates the parts of an array variable declaration and initialization, and the resulting memory representation.
Figure 3.3: An array variable is declared and initialized, and the result is stored in.