call by value : Java Glossary

*0-9ABCDEFGHIJKLMNOPQRSTUVWXYZ (all)

call by value
When you call a method, the method sees a copy of any primitives passed to it. Thus any changes it makes to those values have no effect on the caller’s variables. This also applies to references passed as parameters. The caller cannot change the caller’s reference variables, i.e. make them point to different objects, but it can change the fields in the caller’s objects they point to. In Java, you cannot pass objects as parameters, only references to objects.

Java was designed this way on purpose after decades of experience with lower-level languages that let a callee meddle with a caller’s variables. Java code is much easier to understand because it is more encapsulated. You don’t have to concern yourself with unexpected side effects on your variables with every method call.

The following explanation may be helpful to people with experience with low-level languages such as assembler or FORTH, or for people who have poked around learning how Java byte code works. Java evaluates primitive method argument expressions and pushes them to the return stack. Java pushes argument references to Objects as 32 or 64-bit addresses to the return stack. The callee wakes up with the pushed parameters in its stack frame, where it also stores temporary/local/stack variables. Then, when the callee returns, it pops the stack discarding all the arguments. This is why, even if the callee modifies a parameter variable, it has no effect on the caller’s variables. The modification just affects the copy on callee’s stack frame.

However, changes made to Object fields will be see by the caller.


This page is posted
on the web at:

http://mindprod.com/jgloss/callbyvalue.html

Optional Replicator mirror
of mindprod.com
on local hard disk J:

J:\mindprod\jgloss\callbyvalue.html
logo
Please the feedback from other visitors, or your own feedback about the site.
Contact Roedy. Please feel free to link to this page without explicit permission.
no blog for this page
IP:[65.110.21.43]
Your face IP:[54.235.29.110]
You are visitor number