16 Mar 1996


A variable holds data. It has a name, a type, and a value.

As in any other language, local variables, including arguments, can be defined within a method (function, subroutine, or program). Java's use of local variables is essentially the same as C, except that variable definitions don't have to all come at the start of a method. A variable can be defined in the middle of a function, and can then be used in subsequent statements up to the end of the block in which it was created.

Variables can also be fields in a class. The field variables of a class can be referenced by simple, unqualified names within any of the method functions of the class. Field variables are classified as static or instance variables.

A field variable declared with the keyword static is allocated storage within the class itself. It is initialized when the class is loaded. It acts as a global variable shared by all the methods of the class, and if it is declared public it is shared by all parts of the program.

All of the field variables that are not declared to be static become part of a dynamically allocated object that is an instance of the class. This is the core of object oriented programming.

class Date {

public byte month;
public static byte max_month=12;
public byte day;
public static byte max_day=31;
public short year;


In this example, the class Date has only variable fields (no methods). The two static field variables, max_month and max_day, are created and assigned their initial values when the class itself is loaded from the library. These field variables are then shared by all programs that use the class.

The non-static field variables, month, day, and year, become fields of any dynamically created object of the Date class. They are called instance variables, and the object in which they are stored is an instance of the class. When such an object is created, it will contain a byte to hold the month, a byte to hold the day, and two bytes to hold the year. Every object also has internal housekeeping fields from the interpreter to identify the class to which it is related.

An object is created with the new operation, which must be followed by the name of a class.

Each time the new operation is executed, it creates a new object with a new set of dynamic field variables from the class. Each object has a different set of values for month, day, and year.

When used in another program, a static field variable may have to be qualified by the name of the class in which it is defined, as in "Date.max_month". To reference an instance field variable, however, one must supply a reference to a dynamically created object of the class, from which the value of the field can be extracted.

Continue Back PCLT

Copyright 1996 PC Lube and Tune -- Java H. Gilbert

This document generated by SpHyDir, another fine product of PC Lube and Tune.