aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Argument Passing question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Argument Passing question" Watch "Argument Passing question" New topic
Author

Argument Passing question

Lydia Zhang
Greenhorn

Joined: Feb 24, 2002
Posts: 29
I am still not very clear about the Argument Passing. Can someone kindly tell me why the Q6's result is 101 but Q7's is 12.3? What's the difference between them?
class Q6 {
public static void main(String args[]) {
Holder h = new Holder();
h.held = 100;
h.bump(h);
System.out.println(h.held);
}
}
class Holder {
public int held;
public void bump(Holder theHolder) {
theHolder.held++;
}
}
--------------------------------------------------
class Q7 {
public static void main(String args[]) {
double d = 12.3;
Decrementer dec = new Decrementer();
dec.decrement(d);
System.out.println(d);
}
}
class Decrementer {
public void decrement(double decMe) {
decMe = decMe - 1.0;
}
}


Lydia
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
The difference is that, in the first example, you're passing a reference to an object. In the second example, you're passing a copy of a primitive. By passing a reference, you can modify the original object - you can't do that by passing a primitive.
Check out this animation that illustrates this.
Corey


SCJP Tipline, etc.
Lydia Zhang
Greenhorn

Joined: Feb 24, 2002
Posts: 29
Hi Corey,
Thanks for your clarification. Could you tell me more clearly in the first example, which reference to which object? Your animation example is great, but since you used an int and array variables, I feel it's a little bit difference. Thanks!
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by Lydia Zhang:
but since you used an int and array variables, I feel it's a little bit difference.

Actually, it isn't. An array is an object.
The key is that in the line:

You are passing a reference to the Holder object referenced by h. Therefore, within the bump method, you can modify the original object.
Just think of it this way: the variable h within the main method and the variable theHolder within the bump method both reference the same object. Therefore, modifying that object via one of those references will cause that change to be visible via the other variable.
I hope that helps,
Corey
Lydia Zhang
Greenhorn

Joined: Feb 24, 2002
Posts: 29
I finally got it, thank you so much Corey!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Argument Passing question