Sams Teach Yourself C in 21 Days

(singke) #1
Constants ......................................................................................................

A constant is a data item whose value cannot change as the program is executing. Any of
Java’s primitive data types can be used as constants. To create a constant, use the final
keyword in the declaration:
final double INTEREST_RATE = 0.05;
final int MAXIMUM_COUNT = 200;

Declaring and Initializing Variables ..............................................................

To create a variable of a specified primitive type, use the type name followed by one or
more variable names.
double f;
int counter;
byte b1, b2, b3;
You have the option of initializing a variable at the same time it is declared. Simply fol-
low the variable name with the assignment operator (=) and the desired initial value:
double f=1.23;
int counter=0;
byte b1, b2=13, b3;
The initial value must be appropriate for the data type. Either of the following initializa-
tions will cause an error—the first because the value 2000 is too large for type byte, and
the second because type intcannot hold a fractional value.
byte b1=2000;
int counter=1.23;

Variable Scope ..............................................................................................

In Java, variables and other program elements, such as methods and objects, have a
scope. An item’s scope determines where in the program it can be accessed. Scope is
determined by the use of certain keywords in the item’s declaration and the location of
the declaration. If an item is declared inside a method, its access is limited to that
method, and no keywords are applicable. However, for items declared outside a method,
access can be controlled as described here:
•Theprivatekeyword. The item is accessible only within the class where it is
declared.


  • No keyword. The item is accessible in all classes that are in the same package.
    •Theprotectedkeyword. The item is accessible in all classes that are in the same
    package, as well as in subclasses based on the class.
    •Thepublickeyword. The item is accessible anywhere the class is accessible.


710 Bonus Day 4

39 448201x-Bonus4 8/13/02 11:19 AM Page 710

Free download pdf