Variables are places in memory to store values. There are different kinds of variables, and every language offers slightly different characteristics.
Name.
Data Type specifies the kinds of data a variable an store. Java has two general kinds of data types.
byte
, short
,
int
, long
,
float
, double
, char
, boolean
).
String
,
Color
, JButton
, ...).
Java object variables hold a reference (pointer) to the the
object, not the object, which is always stored on the heap.
Scope of a variable is who can see it. The scope of a variable is related program structure: eg, block, method, class, package, child class.
Lifetime is the interval between the creation and destruction
of a variable. The following is basically how things work in Java.
Local variables and parameters are created
when a method is entered and destroyed when the method returns.
Instance variables are created by new
and destroyed
when there are no more references to them. Class (static) variables
are created when the class is loaded and destroyed when the program
terminates.
Initial Value. What value does a variable have when it is created? There are several possibilites.
null
for objects, and false
for booleans.
Declarations are required. Java, like many languages, requires you to declare variables -- tell the compiler the data type, etc. Declarations are good because they help the programmer build more reliable and efficient programs.