Declaring Variables
Home Up Search Java 2 API C++ Resources

Index:

 

Simple Variables

Declaring a variable means telling the compiler that a variable of the specified type exists.

Declaring a variable does not mean that the variable has been given a value!   

Failure to account for the above issue leads to one of the most common run-time error messages encountered by students:  Null Pointer Exception.    This means that the program tried to use a variable that wasn't yet given a value.

The syntax to declare a variable is as such:

[scope] [qualifier] type variable_name;

where

  • "scope" is used to determine the visibility of the variable.   See the pages on Scoping.    A blank means that the variable is scoped to the nearest enclosing curly brace, unless it is a property of a class, when defaults to package visibility.
  • "qualifier" is either blank or "static". "Static" means that the the variable is common to all instantiations and thus can be accessed even if no instance of the class is present.   Otherwise, the variable's value is unique to each particular instantion.
  • type is either a primitive Java type such as int, double, char, or boolean, or the name of a class, such as String, JFrame, etc.
  • variable_name is the name of the variable.

Examples:

int count;
double width;
String   filename;
MyClass x;

Optionally, an initial value for the variable can be specified:

int maxCount = 23;
boolean flag = true;
String name = "Ishmael";
JFrame infoFrame = new JFrame();
JContainer display = new JPanel();

Notice that for variables refering to objects, they must be initialized with an instantiation of the specified class.   See the pages on instantiating classes.

The last example above is in seeming contradiction to the previous statement.   However, it is a perfectly valid Java statement because it is, in fact, not in contradiction at all.  Why?  See the pages on inheritance and polymorphism.

Values vs. References

It is important to understand that variables refering to Java primitive directly hold the values, however variables referring to objects hold a reference to the object, not the object itself.  Consider the following scenario:

int x = 5;
int y;
y = x;
y = 3;

At this point, x has the value 5 but y has the value 3 because y=x transfered the value of x.

Contrast that situation with this one, which involves one instance of a MyClass object and two variables:

class MyClass
{
      int data;
}

MyClass m = new MyClass();
m.data = 5;
MyClass n;
n = m;
n.data = 3;

At this point n.data has the value 3, and since m and n refer to the same instance of MyClass, m.data also has the value of 3, not 5.   The statement, y=x simply causes y to refer to the same object as x.  

Failure to take this behavior into account leads to a problem called "aliasing" wherein objects unexpectedly change because there are other references to them.

Arrays   

  •   An array is a contiguous set of object references  (or values, for primitives).  They have the advantage of 
    • Random access capable  -- high speed access
    • Minimal memory requirements
  • Array is technically an object
    • Knows its own length:  array_name.length -- helps minimize "array out of bounds" errors.
  • Pitfalls
    • Falling off the end of the array -- "index out of bounds"
    • Uninitialized elements -- java does not automatically initialize the elements of an array.    The creating the array object does not fill the elements with objects.
    • Forces external iteration and use of conditionals because of loss of polymorphic capabilities -- potentially serious architecture ramifications.

Arrays are size and speed at a price

1-dimensional array syntax

Declaration(many different ways to declare an array):

  1. MyClass[] a; // array of MyClass objects, uninitialized
  2. MyClass b[]; // array of MyClass objects, uninitialized
  3. MyClass[] c = new MyClass[5]; // array of 5 elements of type MyClass, all uninitialized
  4. MyClass d[] = {new MyClass(), new MyClass(), new MyClass(), new MyClass(), new MyClass()};   // array of 5 MyClass objects, all initialized to instantiated objects.
  5. new MyClass[] {new MyClass(), new MyClass(), new MyClass(), new MyClass(), new MyClass()}    // anonymous declaration of an array of 5 MyClass objects, all initialized to instantiated objects.

 

Multi-dimensional Arrays

Multi-dimensional arrays are really just arrays of arrays.  In such, they are not required to be rectangular.  For instance, the rows of a 2-dimensional array may each have a different length.

Accessing the elements of a multi-dimensional array is a simple extension of that for the one-dimensional case:

mArray[i][j][k]  refers the k'th element of the j'th array of the i'th array of mArray.     That is, mArray consists of an array of elements, where it's i'th element is an array whose j'th element is an array.   We are looking at the k'th element of that last array.

Syntax examples:

  1. int[][]  myArray = new int[5][42];  //   a rectangular array of ints with 5 rows and 42 columns per row.
  2. float[][][] fArray = new float[7][][];   // Only the leftmost (the lowest level array) dimension needs to be declared.   This is an 3-D array of 7 rows, each of which is a two dimensional array.

The following is legal syntax to initialize a mult-dimensional array:

double[][] dArray = new double[5][]; // new 2-D array of 5 rows and unspecified columns.

dArray[3] = new double[2];  // make this row have 2 colums.

dArray[4] = new double[6];  // make this row have 6 columns.

As usual, beware of uninitialized array elements!