File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes parameter passing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "parameter passing" Watch "parameter passing" New topic

parameter passing

vinita Kh
Ranch Hand

Joined: Feb 19, 2002
Posts: 49
Marcus Green test-II
y the answer is 4 not 2
if we r assigning v.i= 30 in amethod(), then in that method is should print its value as 30, even though we have passes this instance to some other method which modifies this by using this instance.
ne help?
class ValHold{
public int i = 10;
public class ObParm{
public static void main(String argv[]){
ObParm o = new ObParm();
public void amethod(){
int i = 99;
ValHold v = new ValHold();
System.out.print( v.i );
}//End of amethod
public void another(ValHold v, int i){
v.i = 20;
ValHold vh = new ValHold();
v = vh;
}//End of another
1) 10030
2) 20030
3) 209930
4) 10020
Gautam Sewani
Ranch Hand

Joined: Apr 19, 2002
Posts: 93
Its a simple question.You pass v to another().In java,the references of Objects are passed.In another(),you modify the value of i of v.(v.i=20)
Then you change the value of v itself.But before that the value of i has been changed!
This changed is reflected in the original v as references of objects are passed,and changes made through that reference are reflected back in the original reference.
Therefore,the answer is 4.
Hope that helps
John Wetherbie

Joined: Apr 05, 2000
Posts: 1449
Another way to put it is that in Java object references and primitives are passed by value. In the case of the object reference you can change the value of members of the object and these will be reflected outside the scope of the method (since what you have inside the method is a copy or alias). Changing what the object reference refers to will NOT be reflected outside the method.

The only reason for time is so that everything doesn't happen all at once.
- Buckaroo Banzai
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Take a look at this Flash app. I built it to illustrate what is happening in this exact case.
I hope that helps,

SCJP Tipline, etc.
I agree. Here's the link:
subject: parameter passing
It's not a secret anymore!