Hello
My question is, I thought once you try to change the value of the local variable itself, e.g s++ or s = a, the reference starts pointing to a new object. So how come in this question, cA[1] in m1() and cA[1] in m2() are still pointing to the same object when the following occurred in m2(): cA[1] = cA[0] = 'm';
Tariee wrote:Hello
My question is, I thought once you try to change the value of the local variable itself, e.g s++ or s = a, the reference starts pointing to a new object. So how come in this question, cA[1] in m1() and cA[1] in m2() are still pointing to the same object when the following occurred in m2(): cA[1] = cA[0] = 'm';
What you say is true but there is an important point that you are missing.
cA is a reference to an array object. But the elements of that array are not references to other objects because this is an array of chars, which is a primitive. Therefore, cA[1] and cA[0] are not references. They are merely values. That is why, when you change cA[0], you are changing its value right there.
You should try running the same code after changing char arrays to Object arrays and then see what happens.
The explanation to this answer states that "So instance member 'c' keeps its default (i.e. 0) value." But it is not true - the default char value is not 0 but '/0000', this is, null. Here you get zero, because the char is cast to int.
The following snippet prints nothing:
char is an integral type just like byte, short, and int. Its default value is 0. '/0000' is just another way to write it Java code in character format. Internally, it stores 0. There is no difference between the two.
But the point is that the code is printing "0,m" because the char is cast to int, not because c keeps its default value. Without the cast, the code prints ",m". There may not be difference between the two internally, but when printed out the output is different.
In the line of code above, instance variable c is accessed without prefixing any object. I thought only static variables could be accessed directly (without object). Can you please help me in my confusion? Thanks.
When there is no explicit object reference, an implicit reference "this" is supplied by the compiler for instance variable. So "c" is actually "this.c". You should read about this reference here: http://stackoverflow.com/questions/3728 ... is-in-java
No, in Java, everything is passed by value. But in case of objects (any object, including arrays) it is the value of the reference that is passed by value. It is a very important topic so I will suggest you to go through a good book to understand it. Here are a few good links -
horst1a wrote:And why does the compiler not put an implicit this before the c in m2()
Because a variable named c is already in scope. The compiler tries using "this" (or the classname to use the static variable) only if it is not able to resolve the given variable. Here, it is already able to resolve c as a method parameter. So there is no need to use "this".