Java Reference
In-Depth Information
17.
// Read an illegal position
18.
System.out.println("Value at -4 is "+myArray.getValue(-4));
19.
20.
}
21. }
Here is the result of the test run of FlexArrayDriver :
Value at -2 is -8
Value at 2 is 8
ERROR in FlexArray: Index out of bounds.
Value at -4 is 0
Now let us look at a frequently made mistake. We only add one word in the con-
structor of FlexArray .Wereplace the line
data = new int [length];
by
int [] data = new int [length];
The resulting class is called WrongFlexArray and the driver is WrongFlexArray-
Driver .Wedonot print the listing, as it differs only in that one line and the fact
that FlexArray is replaced by WrongFlexArray everywhere. Here is the result of
the test run:
java.lang.NullPointerException
at its.General.WrongFlexArray.setValue(WrongFlexArray.java:70)
at its.General.WrongFlexArrayDriver.main(WrongFlexArrayDriver.java:18)
Exception in thread "main"
What has happened? Why is there a NullPointerException when we want to set
a value in the data array? Well, the data array is not defined. At least not the data
array we want to use in method setValue . The problem lies in the constructor of
WrongFlexArray .Inthe line
int [] data = new int [length];
another local integer array by the name 'data' is defined . This has nothing to do
with the integer array by the name 'data' which is declared before the construc-
tor. The local array ceases to exist when the constructor is finished. Then the
'data' array which is declared before the constructor is still there, but not created
by using new and thus null . When method setValue tries to access it a Null-
PointerException is triggered.
Search WWH ::




Custom Search