Java Reference
In-Depth Information
a. double[] a = new double[10];
System.out.println(a[0]);
b. double[] b = new double[10];
System.out.println(b[10]);
c. double[] c;
System.out.println(c[0]);
C OMMON E RROR 7.1: Bounds Errors
The most common array error is attempting to access a nonexistent position.
double[] data = new double[10];
data[10] = 29.95;
// Error-only have elements with index values 0 ... 9
When the program runs, an out-of-bounds index generates an exception and
terminates the program.
This is a great improvement over languages such as C and C++. With those
languages there is no error message; instead, the program will quietly (or not so
quietly) corrupt the memory location that is 10 elements away from the start of the
array. Sometimes that corruption goes unnoticed, but at other times, the program
will act flaky or die a horrible death many instructions later. These are serious
problems that make C and C++ programs difficult to debug.
291
292
C OMMON E RROR 7.2: Uninitialized Arrays
A common error is to allocate an array reference, but not an actual array.
double[] data;
data[0] = 29.95; // ErrorȌdata not initialized
Array variables work exactly like object variablesȌthey are only references to the
actual array. To construct the actual array, you must use the new operator:
double[] data = new double[10];
Search WWH ::




Custom Search