Java Reference
In-Depth Information
system.out.println (e1.count + e2.count);
}
}
Explanation :
This time we have assigned value of e1 into e2. In fact it is not only value but the whole
object e2 is now referencing to the same memory location as that for e1. In next operation,
we are increasing value contained in e2 by 1. What value e2 will hold now? It should be
5. Why? Because when we put e2 at the same memory location as e1 (through assignment
e2 = e1) the value of e2 had become 4 (same as e1). Now if you run your program then on
your screen the value will be shown as 10 (5+5). Surprised? You may have expected that
e1.count = 4 and e2.count = 5. But this is wrong. The answer is e1.count = 5 and e2.count
= 5.
It may seem outrageous. How come e1.count is 5 and not 4? The answer is that object e1
does not exist after you did assigned e1 to e2. Now e1 and e2 are the same thing. They are
now pointing at same point in memory and the value at this point is 5. If you try doing the
same assignment with variables instead of objects, you will the result as 9. It is because
when you define 2 variables and even if you assign one variable to another, only the value
contained in one variable is assigned to the another variable but the 2 variables will still
point to 2 memory locations.
Now you should be able to understand from this explanation that objects are assigned
through reference whereas variables are assigned through value. Always be careful about
assignment operations with objects.
Search WWH ::




Custom Search