Variables

A variable is used to store data in the computer's memory, which can later be used by the program. Radius and area are examples of variables in the Circle class.

A declaration associates a variable with a type. For example, in line 10,
int radius;
declares an int type variable named radius. Any number of variables can be declared with a single data type so

int radius, diameter;


is a valid declaration. However, it is good practice to have one declaration per line. This makes it easier to add comments or to subsequently change a variable's data type. A variable can be assigned a value in the declaration. For example,
int radius = 5;


declares an integer variable radius and assigns it a value of 5. Of course, an alternative is to have separate declaration and assignment statements, as follows:
int radius;
... other variable declarations
radius = 5;


A variable is an example of an identifier. An identifier is a named item that could be a variable, class, object, and method— in fact, any Java construct. For example, Circle is a class identifier. An identifier can consist of an unlimited number of letters, digits, and underscores, but must start with a letter or underscore. A number of words are reserved by Java and cannot be used as identifiers; these are shown in Table 2.1.

As well as following the rules about identifiers, variables must also be unique within their scope. For example, within the scope of the main method of the Circle class, there can
be only one variable named radius. A second declaration of radius, of type float, say, is illegal and would be rejected by the compiler.

No comments:

Post a Comment