my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes passing parameters to a method. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "passing parameters to a method." Watch "passing parameters to a method." New topic
Author

passing parameters to a method.

cs singh
Ranch Hand

Joined: Dec 28, 2005
Posts: 36


Answer is 3, and the reason is that if we pass the entire array as an object to amethod, any change to it will be reflected on return from the method call .( i donno but in the above code the return type is void.).
Is the above stmt. true in that case also??

One more query, can anybody tell in which case the change is reflected back and in which its not.


Thanks,
Chani.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
All parameter passing in Java is by value. When the formal parameter is an object reference, then a copy of the reference is sent to the method. Anything you do to the copy will affect the object referred to by the actual parameter unless you point the reference somewhere else.
Murali Mohan
Ranch Hand

Joined: Jan 09, 2006
Posts: 66
public class Change{
public void changeIt1(B temp)
{
temp.i=10;
}
public void changeIt1(B temp)
{
temp=new B();
temp.i=10;
}
public static void main(String args[])
{
B obj1,obj2;
obj1=new B();
obj2=new B();
change c=new Change()
c.changeIt1(obj1);
c.changeIt2(obj2);
System.out.println("obj1.i="+obj1.i+" obj2.i="+obj2.i);
}
}


public class B{
public int i=5;
}

The out put of running class Change is
obj1.i=10 obj2.i=5

This is because temp in changIt1 and obj1 in main refers to the same object.
But temp in changeIt2 is reassigned a new objects reference. so temp in ChangeIt2 now donot refers the same object that is refered by obj2 in main. so object refered by obj2 is not changed inside ChangeIt2.
Please let me know if I am wrong.


Thanks,<br />Murali...
Melanie Jones
Greenhorn

Joined: Dec 16, 2005
Posts: 21
You're understanding is right!!

Just a little change in your code and everything will sync in..



- Mel
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: passing parameters to a method.