Object references as method parameters

Object references as method parameters  
 
Take the following example  
 
class ValHold{  
public int i = 10;  
}  
 
public class ObParm{  
public static void main(String argv[]){  
ObParm o = new ObParm();  
o.amethod();  
}  
 
public void amethod(){  
ValHold v = new ValHold();  
v.i=10;  
System.out.println("Before another = "+ v.i);  
another(v);  
System.out.println("After another = "+ v.i);  
}//End of amethod  
 
public void another(ValHold v){  
v.i = 20;  
System.out.println("In another = "+ v.i);  
}//End of another  
}  
 
 
The output from this program is  
 
Before another = 10  
In another = 20  
After another = 20  
 
 
 
I am looking to above program from link  
 
http://www.jchq.net/certkey/0504certkey.htm   
 
I have not clearly understood the output.  
 
Why it is 20 after another as well.  
 
Any ideas, resources,sample code,links, highly appreciated. thanks in advance.
LVL 7
gudii9Asked:
Who is Participating?
 
for_yanConnect With a Mentor Commented:


@objects:
I'm not sure, I understand your last remark.

I tried, and this does not throw exception:

public class LabLoop{
    public static void main(String argv[]){

        LabLoop m = new LabLoop();
        LabLoop n = new LabLoop();

        m = n;

        n = null;

        m.amethod();
}

public void amethod(){

}

}

Open in new window


whereas this obviously does throw exception:


public class LabLoop{
    public static void main(String argv[]){

        LabLoop m = new LabLoop();
        LabLoop n = new LabLoop();

        m = n;

        n = null;

        n.amethod();
}

public void amethod(){

}

}

Open in new window



0
 
CEHJConnect With a Mentor Commented:
>>
I have not clearly understood the output.  
 
Why it is 20 after another as well.  
>>

Because having a reference to an object is all you need to change its fields if they are in scope. another() changed it to 20 and nothing changed it back again
0
 
for_yanCommented:
because you pass just the reference to the another method - there is only one object v,
Then iside another() method you chnge the value of instance variable within the same and the only
physical object, so you don't need to return this object back; the same referrence referwes to the same object in the
calling method, but instance varible within that method another already changed inside the same object.
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
CEHJCommented:
>> if they are in scope.

should have said

 if you have access to them.
0
 
objectsCommented:
> Why it is 20 after another as well.  

because another changes the value to 20

> v.i = 20;  

The fact that v is passed as a parameter is really irrelevant.
The value is originally 10 , then it gets changed to 20 in the another() method

Let me know specifically whats confusing you if still unclear
0
 
objectsCommented:
Java passes a pointer to the parameter, so the object that is being updated in the method is the same object that was passed into the method
So the value will be 20 after the method has been called.
0
 
gudii9Author Commented:
>>>Java passes a pointer to the parameter, so the object that is being updated in the method is the same object that was passed into the method.

>>>Because having a reference to an object is all you need to change its fields if they are in scope
>>>the same referrence referwes to the same object in the
calling method, but instance varible within that method another already changed inside the same object.


can you please elaborate on this
0
 
objectsCommented:
the object that gets passed is the same one updated in the method
what exactly are you unclear about?
0
 
gudii9Author Commented:
which one is gets passed and which one is one updated here?
0
 
objectsCommented:
> another(v);  

v gets passed in and updated
0
 
for_yanCommented:

You can think of a variable which represents some Java object, as an address to
the memory cell where java begins storing information about the fileds which are contained
in this object.  Say object v in your example starts at certain location, and once you know this location
you can find the place where your variable i is sitting (let's say it is some fixed number of cells
further than the beginnig of the object).

so when you pass this object to method you just communicate to that
method this address wher the object begins. You do not create a new copy of object,
all the same locations of memory are occupioed by this object.
So when inside the method you change variable i - the value in that location
where it was siting, is now different, and no matter where you access
this object from another() method or from your calling method (amethod())
you still point to the same object in the same location and you'll see a changed value of this variable i
in that very unique cell, where this variable is living
0
 
gudii9Author Commented:
>>so when you pass this object to method you just communicate to that
method this address wher the object begins.

what you mean object begins.



>>>  Say object v in your example starts at certain location, and once you know this location
you can find the place where your variable i is sitting (let's say it is some fixed number of cells
further than the beginnig of the object).


(So when inside the method you change variable i - the value in that location
where it was siting, is now different, and no matter where you access
this object from another() method or from your calling method (amethod())
you still point to the same object in the same location and you'll see a changed value of this variable i
in that very unique cell, where this variable is living)



what happens you assign this object instance to other object.  does the cells remain same i mean very unique cell. but much further than beginning of object right.




I am confused
please advise
0
 
for_yanCommented:

Think of object as it is stored in memory as a consecutive set of memory cells,

for example

class Person {

String name;

float age;

String address;

}

Let's think in memory the instance of object Person will
occupy 200 bytes.

Let's think it starts at some location in memory -
for simplicity - it will be location number 500
So 500 is the address of the beginnig of some particular Person object.

The in location 500 the last name string will start.
It will occupy 60 bytes. In location 560 will start age - it will occupy
20 bytes more and in location 580 will start address
which will occupy 120 bytes - so this person instance will occupy
locations from 500 to 700.

If you have another instance of person in memory - it may start say
at location 2000, but all ofssets will be the same, which means that last name
will start at locatioo 2000, age - at location 2060, and address at location 2080
and the instance will end at location 2200.

Now when I pass first isntance to the method - the only thing I communicate
to the method isthe beginning location - number 500.
And Java knows the layout of the class, so it can easily
calculate wher is last name, where is age and where is address.

suppose method is deigned to add one year to the age
of the person - it will figure out that age begins at location 560
it will read the age from that location, add 1 to the number and store it again to the same
location 560.

Now back in the calling method java still knows that
the informnation about first of our persons begins at location 500.
Now someone back in the caling program wnats to know the age -
the program goes again to the beginning of the class,
calculates where is the number of years - it is in location 560 - now
it reads this number, and this number was already incremeneted by the method
which we called before, so it will read already
incremeneted age. this is because we passed to the method only the address
of our object, we didn't make a copy of any of the contents,
We had befiore and still have only one location where we have
the age of this first person store - this is cell number 560 in our memory.
thats what is meant by passing arguments by reference.

I hope you now understand what means "object begins" - it is a place
where object begins in memory.

In fact memory is organized in much more complex way - but don't worry
about it - this simple model is quite sufficient to understand
all about passing object by reference





0
 
gudii9Author Commented:
what happens you assign this object instance or reference to other object.  does the cells remain same i mean very unique cell. but much further than beginning of object right.

like

Object a= new Object();

Object b= new Object();

what happens when you say with respect cell number, location. please advise
a=b;


0
 
objectsCommented:
Object a= new Object();
Object b= new Object();

creates 2 new objects, one referenced by a, the other by b

a=b;

Now both a and b reference the same object

0
 
for_yanCommented:

When you create new objects like that

Object a= new Object();
Object b= new Object();

Each one points to different instance. Each of the two instances
starts from its own place like two different persons in our example and can potentially have different properties

However when you assign

a=b;

That means that variable a and variable b now point to the same location, therefore they refer to the starting location of
the same object. After this assignment we effectively lost the handle to the first object and in fact we can now work only with one of the objects. The first object becomes no longer accessible.
0
 
gudii9Author Commented:
>>>a=b;

Now both a and b reference the same object



if you say b=null;

then a is eligible for garbage colection at this line since ' a' in stack is also disconnected from object on heap right.

>>>  Say object v in your example starts at certain location, and once you know this location
you can find the place where your variable i is sitting (let's say it is some fixed number of cells
further than the beginnig of the object).


is this is 'what java pass by value'



please advise

0
 
for_yanCommented:

Yes after operator
 a=b;
a and b reference thesame object - this is true,

but if after that you say b = null;
then b references nothing from this point, but a still references your object,
therefore object still has a handle and it cannot be garbage collected, at least untill you say a = null

-------
>>>  Say object v in your example starts at certain location, and once you know this location
you can find the place where your variable i is sitting (let's say it is some fixed number of cells
further than the beginnig of the object).


is this is 'what java pass by value'
---
This is what I explained here is how
java passes object v to the method by reference - it passes
only the address of the object to the method

When java passes primitive types (e.g. integer, float numbers)
by value it creates a copy of the value - it makes a new memory cell which
contains the same value - and this copy memory cell is actually passed to the method,
therefore if inside method this cell is changed, then the value
of this variable in the calling method will not change, as the calling method
deals with that original cell containing original value.

When objects are passed by reference - no physical copy of the object
is created and only address opf the object is communicated to the method,
therefore if you change some field value inside the method
and originating calling code choosed to retrive the value from the same
location it will see changed value -

this is the main deifference in
passing parameters by value and by reference
 
0
 
objectsConnect With a Mentor Commented:
> then a is eligible for garbage colection at this line since ' a' in stack is also disconnected from object on heap right.

correct

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.