Java Reference
In-Depth Information
Statementa=b executed.
Valuea=4
Valueb=4
Statementb=7 executed (new value for b).
Valuea=4
Valueb=7
Let us now look at what happens if we use objects. The following code snippet
uses arrays of integers instead of integers. Arrays are objects in Java. We use
arrays of length two and apply the same operations as above to the elements at
array position 1. Below is a listing of the code and output.
Code snippet:
int[]A={1,3};
int[]B={1,4};
A=B;
B[1] = 7;
Listing of output:
Value A[1] = 3
Value B[1] = 4
StatementA=B executed.
Value A[1] = 4
Value B[1] = 4
Statement B[1] = 7 executed (new value for B[1]).
Value A[1] = 7
Value B[1] = 7
The behaviour is not as one might have expected. After we set the entry at position
1inarray B to 7 , the entry at position 1 in array A is also 7 .Wewould expect A[1]
to be 4 . The reason for this is that the statements a=b in the first code snippet
and A=B in the second one have different semantics and thus different results.
Figure B.1 shows what happens if we use integers. The names a and b always
refer to the integer value. Therefore the statement a=b means ' a is assigned the
value of b '.
int a = 3
a 3
b 4
a 3
int b = 4
b 4
a = b
a 4
b = 7
a 4
b 7
Figure B.1 A visualization of the first code snippet. The Java statements are listed on the
left and the results are on the right. A rectangle symbolizes a memory location and the letter
inside is the variable name
Search WWH ::




Custom Search