Passing Object Reference Variables

Passing Object Reference Variables

When we pass an object variable in to a method , We must know that we\'re passing the object reference, and not the actual object itself.

We must remember that we are not even passing the actual reference variable, but rather a copy of the reference variable.

The copy variable means we get the copy of the bits in that variable, so when we pass a reference variable,

We can also say like this : both the caller and the called method will now have identical copies of the reference, and thus both will refer to the same exact (not a copy) object on the heap.

For this example, we will use the Dimension class from the java.awt package:


1. import java.awt.Dimension;
2. class ReferenceTest {
3. public static void main (String [] args) {
4. Dimension d = new Dimension(5,10);
5. ReferenceTest rt = new ReferenceTest();
6. System.out.println(\"Before modify() d.height = \" + d.height);
7. rt.modify(d);
8. System.out.println(\"After modify() d.height = \" + d.height);
9. }
10. void modify(Dimension dim) {
11. dim.height = dim.height + 1;
12. System.out.println(\"dim = \" + dim.height);
13. }
14. }

When we run this class, we can see that the modify() method was indeed able to modify the original (and only) Dimension object created on line 4.

C:Java ProjectsReference>java ReferenceTest
Before modify() d.height = 10
dim = 11
After modify() d.height = 11

By:UMANG
Date:2027-02-09 00:00:00

Post Your Answers


User Email:

User Name:
Answers:

Related scjp1.5 chap3 Links

scjp1.5 chap3 interview questions and answers for experienced and fresher