Variables
An object stores its state in variables.
Definition
A variable is an item of data named by an identifier.
You must explicitly provide a name and a type for each variable you want to use in your program. The variable's name must be a legal identifieran unlimited series of Unicode [1] characters that begins with a letter. You use the variable name to refer to the data that the variable contains. The variable's type determines what values it can hold and what operations can be performed on it. To give a variable a type and a name, you write a variable declaration, which generally looks like this:
[1] Unicode is a 16-bit character set defined by ISO 10646.
type name
In addition to the name and the type that you explicitly give a variable, a variable has scope. The section of code where the variable's simple name can be used is the variable's scope. The variable's scope is determined implicitly by the location of the variable declaration, that is, where the declaration appears in relation to other code elements. You'll learn more about scope in the section Scope (page 72).
The boldface type in the following program, called MaxVariablesDemo, [2] highlights all the variable declarations in the program: [2] MaxVariablesDemo.java is included on the CD and is available online. See Code Samples (page 117). |
public class MaxVariablesDemo { public static void main(String args[]) { // integers byte largestByte = Byte.MAX_VALUE; short largestShort = Short.MAX_VALUE; int largestInteger = Integer.MAX_VALUE; long largestLong = Long.MAX_VALUE; // real numbers float largestFloat = Float.MAX_VALUE; double largestDouble = Double.MAX_VALUE; // other primitive types char aChar = 'S'; boolean aBoolean = true; // display them all System.out.println("The largest byte value is " + largestByte); System.out.println("The largest short value is " + largestShort); System.out.println("The largest integer value is " + largestInteger); System.out.println("The largest long value is " + largestLong); System.out.println("The largest float value is " + largestFloat); System.out.println("The largest double value is " + largestDouble); if (Character.isUpperCase(aChar)) { System.out.println("The character " + aChar + " is upper case."); } else { System.out.println("The character " + aChar + " is lower case."); } System.out.println("The value of aBoolean is " + aBoolean); } }
The output from this program is:
The largest byte value is 127 The largest short value is 32767 The largest integer value is 2147483647 The largest long value is 9223372036854775807 The largest float value is 3.40282e+38 The largest double value is 1.79769e+308 The character S is upper case. The value of aBoolean is true
The following sections further explore the various aspects of variables, including data types, names, scope, initialization, and final variables. The MaxVariablesDemo program uses two items with which you might not yet be familiar and are not covered in this section: several constants named MAX_VALUE and an if-else statement. Each MAX_VALUE constant is defined in one of the number classes provided by the Java platform and is the largest value that can be assigned to a variable of that numeric type. These classes are covered in the section The Number Classes (page 150). The if-else statement is covered later in this chapter in the section The if-else Statements (page 102).
Data Types
Every variable must have a data type. A variable's data type determines the values that the variable can contain and the operations that can be performed on it. For example, in the MaxVariablesDemo program, the declaration int largestInteger declares that largestInteger has an integer data type (int). Integers can contain only integral values (both positive and negative). You can perform arithmetic operations, such as addition, on integer variables.
The Java programming language has two categories of data types: primitive and reference. A variable of primitive type contains a single value of the appropriate size and format for its type: a number, a character, or a boolean value. For example, an integer value is 32 bits of data in a format known as two's complement, the value of a char is 16 bits of data formatted as a Unicode character, and so on.
Figure 41. A variable of primitive type contains a value of a particular size and format.
Table 3 lists, by keyword, all the primitive data types supported by the Java platform, their sizes and formats, and a brief description of each. The MaxVariablesDemo program declares one variable of each primitive type.
Keyword |
Description |
Size/Format |
|
---|---|---|---|
Integers |
byte |
Byte-length integer |
8-bit signed two's-complement integers |
short |
Short integer |
16-bit signed two's-complement integers |
|
int |
Integer |
32-bit signed two's-complement integers |
|
long |
Long integer |
64-bit signed two's-complement integers |
|
Real Numbers |
float |
Single-precision floating point |
32-bit IEEE 754 floating-point numbers |
double |
Double-precision floating point |
64-bit IEEE 754 floating-point numbers |
|
Other Types |
char |
A single Unicode character |
16-bit Unicode character |
boolean |
A boolean value (true or false) |
8-bit/1-bit (8 bits of space, 1 bit of data) |
[a] The size and format information is provided for experienced programmers who like details of this sort. If you don't know what two's complement or IEEE 754 is, don't worry about it. You don't need to.
Purity Tip
In other programming languages, the format and the size of primitive data types can depend on the system on which the program is running. In contrast, the Java programming language specifies the size and the format of its primitive data types. Hence, you don't have to worry about system dependencies.
You can put a literal primitive value directly in your code. For example, if you need to assign the value 4 to an integer variable, you can write this:
int anInt = 4;
The digit 4 is a literal integer value. Table 4 gives some examples of literal values of various primitive types.
Literal |
Data Type |
---|---|
178 |
int |
8864L |
long |
37.266 |
double |
37.266D |
double |
87.363F |
float |
26.77e3 |
double |
' c' |
char |
true |
boolean |
false |
boolean |
Generally speaking, a series of digits with no decimal point is typed as an integer. You can specify a long integer by putting an 'L' or 'l' after the number. 'L' is preferred, as it cannot be confused with the digit '1'. A series of digits with a decimal point is of type double. You can specify a float by putting an 'f' or 'F' after the number. A literal character value is any single Unicode character between single quote marks. The two boolean literals are simply true and false.
Arrays, classes, and interfaces are reference types. The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable (Figure 42). A reference is called a pointer, or a memory address in other languages. The Java programming language does not support the explicit use of addresses like other languages do. You use the variable's name instead.
Figure 42. A variable of reference type contains a reference to (an address of) an object or an array.
Variable Names
A program refers to a variable's value by the variable's name. For example, when it displays the value of the largestByte variable, the MaxVariablesDemo program uses the name largestByte. A name, such as largestByte, that's composed of a single identifier, is called a simple name. Simple names are in contrast to qualified names, which a class uses to refer to a member variable that's in another object or class. This topic is covered further in the section Using Objects (page 126).
In the Java programming language, the following must hold true for a simple name.
- It must be a legal identifier. Recall from page 67 that an identifier is an unlimited series of Unicode characters that begins with a letter.
- It must not be a keyword, [1] a boolean literal (true or false), or the reserved word null.
[1] All the keywords in the Java programming language are listed in the section Java Programming Language Keywords (page 535).
- It must be unique within its scope. A variable may have the same name as a variable whose declaration appears in a different scope. In some situations, a variable may share names with another variable, which is declared in a nested scope. Scope is covered in the next section.
By Convention
Variable names begin with a lowercase letter, and class names begin with an uppercase letter. If a variable name consists of more than one word, the words are joined together, and each word after the first begins with an uppercase letter, like this: isVisible. The underscore character (_) is acceptable anywhere in a name, but by convention is used only to separate words in constants (because constants are all caps by convention and thus cannot be case-delimited).
Scope
A variable's scope is the region of a program within which the variable can be referred to by its simple name. Secondarily, scope also determines when the system creates and destroys memory for the variable. Scope is distinct from visibility, which applies only to member variables and determines whether the variable can be used from outside of the class within which it is declared. Visibility is set with an access modifier. See the section Controlling Access to Members of a Class (page 193) for more information.
The location of the variable declaration within your program establishes its scope. There are four categories of scope, as shown in Figure 43.
Figure 43. The four categories of scope: member variable, method parameter, local variable, and exception-handler parameter.
A member variable is a member of a class or an object. It is declared within a class but outside of any method or constructor. A member variable's scope is the entire declaration of the class. However, the declaration of a member needs to appear before it is used when the use is in a member initialization expression. For information about declaring member variables, refer to the section Declaring Member Variables (page 181).
You declare local variables within a block of code. In general, the scope of a local variable extends from its declaration to the end of the code block in which it was declared. In MaxVariablesDemo, all the variables declared within the main method are local variables. The scope of each variable in that program extends from the declaration of the variable to the end of the main methodindicated by the second to last right brace (}) in the program code.
Parameters are formal arguments to methods or constructors and are used to pass values into methods and constructors. The scope of a parameter is the entire method or constructor for which it is a parameter. The chapter Classes and Inheritance (page 177) discusses writing methods in the section Defining Methods (page 182), which talks about passing values into methods through parameters.
Exception-handler parameters are similar to parameters but are arguments to an exception handler rather than to a method or a constructor. The scope of an exception-handler parameter is the code block between { and } that follow a catch statement. The chapter Handling Errors Using Exceptions (page 243) talks about using exceptions to handle errors and shows you how to write an exception handler that has a parameter.
Consider the following code sample:
if (...) { int i = 17; ... } System.out.println("The value of i = " + i); // error
The final line won't compile, because the local variable i is out of scope. The scope of i is the block of code between the { and }. The i variable does not exist anymore after the closing }. Either the variable declaration needs to be moved outside of the if statement block, or the println method call needs to be moved into the if statement block.
Variable Initialization
Local variables and member variables can be initialized with an assignment statement when they're declared. The data type of the variable must match the data type of the value assigned to it. The MaxVariablesDemo program provides initial values for all its local variables when they are declared. The local variable declarations from that program follow, with the initialization code set in boldface:
// integers byte largestByte = Byte.MAX_VALUE; short largestShort = Short.MAX_VALUE; int largestInteger = Integer.MAX_VALUE; long largestLong = Long.MAX_VALUE; // real numbers float largestFloat = Float.MAX_VALUE; double largestDouble = Double.MAX_VALUE; // other primitive types char aChar = 'S'; boolean aBoolean = true;
Parameters and exception-handler parameters cannot be initialized in this way. The value for a parameter is set by the caller.
Final Variables
You can declare a variable in any scope to be final. The value of a final variable cannot change after it has been initialized. Such variables are similar to constants in other programming languages.
To declare a final variable, use the final keyword in the variable declaration before the type:
final int aFinalVar = 0;
The previous statement declares a final variable and initializes it, all at once. Subsequent attempts to assign a value to aFinalVar result in a compiler error. You may defer initialization of a final local variable. Simply declare the local variable and initialize it later, like this:
final int blankfinal; . . . blankfinal = 0;
A final local variable that has been declared but not yet initialized is called a blank final. Again, once a final local variable has been initialized, it cannot be set, and any later attempts to assign a value to blankfinal result in a compile-time error.
By Convention
Names of constant values are spelled in all capital letters. For example:
final double AVOGADRO = 6.023e23;
Summary of Variables
When you declare a variable, you explicitly set the variable's name and data type. The Java programming language has two categories of data types: primitive and reference. A variable of primitive type contains a value. Table 3 (page 69) shows all the primitive data types along with their sizes and formats. A variable of reference type contains a reference to a value. Arrays, classes, and interfaces are reference types.
The location of a variable declaration implicitly sets the variable's scope, which determines what section of code may refer to the variable by its simple name. There are four categories of scope: member variable scope, local variable scope, parameter scope, and exception-handler parameter scope.
You can provide an initial value for a variable within its declaration by using the assignment operator (=). You can declare a variable as final. The value of a final variable cannot change after it's been initialized.
Questions and Exercises: Variables
Questions
1: |
Which of the following are valid variable names? int anInt i i1 1 thing1 1thing ONE-HUNDRED ONE_HUNDRED something2do |
2: |
Answer the following questions about the BasicsDemo program shown on page 65.
|
Exercises
1: |
Modify the MaxVariablesDemo program shown on page 67 so that aBoolean has a different value. |
2: |
Rewrite the MaxVariablesDemo program to display the minimum value of each integer data type. You can guess what the names of these variables are, or you can look them up in the API documentation. |
3: |
Can you guess the name of a method in the Character class that you can use instead of isUpperCase to determine the capitalization of a character? Modify the MaxVariablesDemo program to use that method instead of isUpperCase. |
Answers
You can find answers to these Questions and Exercises online:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/QandE/answers_variables.html