I am currently studying for the OCA Java 7 Exam. In OCA Java SE 7 Programmer I Study Guide (Exam 1Z0-803) (Oracle Press), by Robert Liguori and Edward Finegan, at the "Understanding Methods and Variable Scope" chapter, I found the statement that Objects are passed to methods by reference and not by value. As far as i know, in Java, the objects are always passed by value. Can someone please explain this?
Life is not measured by the number of breaths we take, but by the moments that take our breath away.
hum, I have a problem with saying objects are passed by reference. Although in practice it is true, accordingly to Kathy Sierra and Bert Bates in the SCJP 6 Study Guide, everything is passed by value in Java, it's just that the "value" of a reference variable would be the reference to the object.
Objects aren't passed at all, only references are. So is the reference passed by reference? Books say different things but recently there's more consensus that Java only supports "pass by value".
Compare with a language that supports "pass by reference" like C# (C# ref):
The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the method is reflected in the underlying argument variable in the calling method. The value of a reference parameter is always the same as the value of the underlying argument variable.
Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference.
Here changing a parameter doesn't mean mutating the object it refers to, but changing its own value by reassigning it. So something like this would be possible:
I try to consistently use the terminology found at the Evaluation Strategy article. It should be noted that, even though the article points out the terms vary greatly by community, it stresses that the semantics for call-by-value and call-by-reference differ in a very crucial way. (Personally I prefer to use call-by-object-sharing these days over call-by-value[-of-the-reference], as this describes the semantics at a high-level and does not create a conflict with call-by-value, which is the underlying implementation.)
William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.