Java Reference
In-Depth Information
affected the value of sirius in main , the "after" line would say " null ".
However, the variable bodyRef in commonName and the variable sirius in
main both refer to the same underlying object, so the change made in-
side commonName is visible through the reference sirius .
Some people will say incorrectly that objects are passed "by reference."
In programming language design, the term pass by reference properly
means that when an argument is passed to a function, the invoked func-
tion gets a reference to the original value, not a copy of its value. If
the function modifies its parameter, the value in the calling code will
be changed because the argument and parameter use the same slot in
memory. If the Java programming language actually had pass-by-refer-
ence parameters, there would be a way to declare halveIt so that the
above code would modify the value of one , or so that commonName could
change the variable sirius to null . This is not possible. The Java pro-
gramming language does not pass objects by reference; it passes object
references by value. Because two copies of the same reference refer to
the same actual object, changes made through one reference variable
are visible through the other. There is exactly one parameter passing
modepass by valueand that helps keep things simple.
You can declare method parameters to be final , meaning that the value
of the parameter will not change while the method is executing. Had
bodyRef been declared final , the compiler would not have allowed you to
change its value to null . When you do not intend to change a paramet-
er's value, you can declare it final so the compiler can enforce this ex-
pectation. A final declaration can also protect against assigning a value
to a parameter when you intended to assign to a field of the same name.
The declaration can also help the compiler or virtual machine optimize
some expressions using the parameter, because it is known to remain
the same. A final modifier on a parameter is an implementation de-
tail that affects only the method's code, not the invoking code, so you
can change whether a parameter is final without affecting any invoking
code.
 
Search WWH ::




Custom Search