|
||||||
|
Index:
Simple VariablesDeclaring 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:
where
Examples:
Optionally, an initial value for the variable can be specified:
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. ReferencesIt 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:
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:
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
1-dimensional array syntaxDeclaration(many different ways to declare an array):
Multi-dimensional ArraysMulti-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:
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!
|