Ask Questions?

View Latest Questions



Posted on: July 26, 2006 at 12:00 AM
Variables are places in memory to store values.

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.

  • 8 basic or primitive types (byte, short, int, long, float, double, char, boolean).
  • An unlimited number of object types (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.

  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.

  • Declarations allow the compiler to find places where variables are misused, eg, parameters of the wrong type. What is especially good is that these errors are detected at compile time. Bugs that make it past the compiler are harder to find, and may not be discovered until the program has been released to customers. This fits the fail early, fail often philosophy.
  • A declaration is also the perfect place to write comments describing the variable and how it is used.
  • Because declarations give the compiler more information, it can generate better code.
Copyleft 2003 Fred Swartz MIT License