Java Notes: Variables

Variables are places in memory to store values. There are different kinds of variables, and every language offers slightly different characteristics.


Data Type specifies the kinds of data a variable an store. Java has two general kinds of data types.

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.

  1. No initial value. Java local variables have no initial value, however Java compilers perform a simple flow analysis to ensure that every local variable is assigned a value before it is used. These error messages are usually correct, but the analysis is simple-minded, so sometimes you will have to assign an initial value even tho you know that it isn't necessary.
  2. User specified initial value. Java allows an assignment of intitial values in the declaration of a variable.
  3. Instance and static variables are given default initial values: zero for numbers, 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.