Re: pass by reference
angelochen960@gmail.com wrote:
Top-posting re-ordered - please don't top-post.
On Apr 4, 9:21 pm, Patricia Shanahan <p...@acm.org> wrote:
Andreas Leitgeb wrote:
Lew <l...@lewscanon.com> wrote:
Thanks for all the answers, I'm kind of surprised that a simple
question got so many answers! is this statement correct:
Everything in Java are passed by value, in the case of an object, a
reference to the object is passed, which is a value too, updating the
fields in the reference does reflect the changes.
Its sort of correct but the language is a bit sloppy and open to
misinterpretation.
anyway, maybe I
should not try to understand java in a C++ manner.
I think you shouldn't. People who do seem to get confused.
but i can't help,
Oh dear.
String is a object,
Yes
so a reference should be the one passed,
Yes, well a copy of the reference is passed.
and why we can not update the field in the String object?
1) Strings don't have any public fields of the sort you imply.
2) Strings are immutable by definition.
Not all objects are immutable (obviously) but Strings are, by intention.
and then where is the field of the String?
This isn't a meaningful question.
Consider ...
main() {
String x = "aaa";
foo(x);
}
static void foo(String s) {
String p = s; // ONE
s = "bbb" // TWO
}
There is an object of class String, having been instantiated it exists
somewhere in memory. Within this chunk of memory is (presumably) the
UCS-2 representation of the characters "aaa".
Just before assignment TWO there are at least three references that
"point" to this object. These three references have three names (x, s
and p). We can say that variables x,s and p contain a reference to the
same object. However s is a copy of x it isn't a reference or pointer to x.
If I were writing a JVM I might have structures not entirely unlike like
this:
After assignment "ONE":
addr contents
000 "x" 122 "s" 177 "p" 127
044 3 "aaa"
122 44
127 44
177 44
After assignment "TWO":
000 "x" 122 "s" 177 "p" 127
044 3 "aaa"
122 44
127 44
177 251
251 3 "bbb"
Notice that changing what s points to has no effect on what x points to.
I expect everyone will be glad I am not writing a JVM.
--
RGB