The code below is from a Java book, from a chapter on Methods and Classes. It apparently illustrates the concept of passing objects by value. The thing is, I can sort of follow what's going on, but:- <B> ob.meth(a, b); </B> - passes the values 10 and 20 to the 'meth' method. OK, but what happens to the values inside of this method? Surely their values are changed?! The program, when run, states that their values have NOT changed! What's going on folks, i'm stuck [again]. Any help would be greatly appreciated. Cheers in advance.
John Bonham was stronger, but Keith Moon was faster.
Joined: Nov 11, 2003
My understanding is that a COPY of a and b are sent to meth. The a and b that are in main() remain unchanged. It's like if I faxed you a document and you took that document and wrote all over it. That COPY has been changed but my original document is the same as it was. Also, meth() looks like it's not returning anything. If you had something like a = meth(a), then you would be sending a copy of a to meth and you could return a result in with which you could then modify a. I'm a Java beginner so don't give this post more weight than it deserves but if it helps that's good too.
Joined: Nov 16, 2003
Hi Steve, From what i can see your problem is that your 'meth' method is void, this means it does not return a value to the method from where it was called. what you need is a method that returns int, e.g.
if you wanted to return a String your method would be:
So, since you are returning values, you can output these in 2 ways, you can create two ints to store your values in: eg
and output value_to... to the user or you can simply go:
I hope this is of some help to you Tony [ November 16, 2003: Message edited by: Tony Matthes ]
author and iconoclast
Cool. I've sussed it, and I wouldn't have had it not been for the input of all those who replied. Cheers folks, thanks for your help. No doubt I'll have loads more problems, as i tackle Java. :roll: Just hope I can post these problems as I encounter them! [ November 16, 2003: Message edited by: Steve Jensen ]
Joined: Aug 20, 2001
Dan, I agree with Ernest: I particularly like the fax analogy. That's it. Just a comment. Nothing more to add.
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Joined: Feb 05, 2003
Keep in mind that if an array is passed to a method, the original value WILL be changed. However, if a single array value (array) is passed, that value is not changed. Is that right, everyone?
-nothing important to say, but learnin' plenty-