Java Reference
In-Depth Information
01
int[] A={1,3}
A
13
01
01
13 B
14
int[] B={1,4}
A
01
01
A
13
B
14
A = B
01
01
A
13
17
B
B[1] = 7
Figure B.2 A visualization of the second code snippet. The Java statements are listed on the
left and the results are displayed on the right. A rectangle symbolizes the memory area of an
array of length 2. The array indices 0 and 1 are shown above. The arrow from the variable
name to the rectangle indicates which array is referenced by the variable name. Here the
statement A=B means that A refers to the same array as B . The array to which A originally
pointed cannot be accessed any more and is therefore shown in grey
Let us now look at the second program snippet. The statement int[] A = { 1,3 }
creates an integer array of length 2. The variable name A is now a reference to the
memory location where the array is stored. It does not refer to any integer value.
It cannot refer to a value because the array holds two values. Thus the statement
A=B means ' A now references the same memory location as B '. Now, changing
B[1] to 7 has the effect that also A[1] is 7 . The originally created array with
entries 1 and 3 is lost. It cannot be accessed any more because there is no reference
pointing to it. Java's automatic garbage collection detects such objects and removes
them from the memory. See also Figure B.2.
The full listing of the program can be found in package its.ReferenceDemo .
B.2
Declarations and definitions
Consider the following class FlexArray .Itimplements an array of integers
where the index is not 0
,
1
,...,
n
1 but a
,
a
+
1
,...,
b for a
,
b
∈ Z
, a
b . Class
FlexArrayDriver shows
how
to
use
the
class.
It
is
located
in
package
its.General .
File: its/General/FlexArray.java
1.
package its.General;
2.
3.
4.
public class FlexArray {
// Here the variable ”data” is DECLARED
5.
// NO array is created! Thus data are null
6.
// at this point. We cannot DEFINE ”data”
7.
// here because we do not know how long the
8.
Search WWH ::




Custom Search