Java Reference
In-Depth Information
Furthermore, this pass-by-reference mechanism limits the risk of function
stack overflow.
To illustate the notion of array references, consider the following set of
instructions:
Program 4.3 Arrays and references
int []v= { 0, 1, 2, 3, 4 } ;
// That is, v[0]=0, v[1]=1, v[2]=2, v[3]=3, v[4]=4;
int []t=v;
// Reference of t is assigned to the reference of v so that t
[i]=v[i]
t[2]++; // Post-incrementation: t[2]=v[2]=3
System . out . println ( t[2]++) ;
// Display 3 and increment t[2]=v[2]=4 now
The result displayed in the console is 3 . In summary, an array is allocated as
a single contiguous memory block. An array variable stores a reference to the
array: This reference of the array links to the symbolic memory address of its
first element (indexed by 0).
Program 4.4 Assign an array reference to another array: Sharing common
elements
class ArrayReference {
public static void main ( String [ ]
args )
{ int [] v= { 0,1,2,3,4 } ;
System . out . println ( "Reference of array u in memory:" +v ) ;
System . out . println ( "Value of the 3rd element of array v:"
+v[2]) ;
// Declare a new array and assign its reference to the
reference of array v
int [] t =v;
System . out . println ( "Reference of array v in memory:" +v ) ;
// same as u
System . out . println (v [ 2 ] ) ;
t[2]++;
System . out . println (v [ 2 ] ) ;
v[2]++;
System . out . println ( t [ 2 ] ) ;
}
}
Running this program, we notice that the reference of the array u coincides
with the reference of array v :
Reference of array u in memory:[I@3e25a5
Value of the 3rd element of array v:2
Reference of array v in memory:[I@3e25a5
2
 
Search WWH ::




Custom Search