Lots of people have asked if Java is "pass-by-reference" or "pass-by-value", yet I feel I haven't gotten a good explanation of how Java actually stores references and how it dereferences them when called.
Would anyone be able to explain what happens when you have something like, say,
public class Foo {
public static void main(String a[]){
Object a = new Object();
Object b = a;
Object c = b;
bar(c);
}
public static void bar(Object obj) {
obj = new Object();
System.out.println(obj);
}
}
in terms of pointers?
How is the JVM actually referencing and dereferencing objects and references?
I'm guessing it's semantically equivalent to the semi-pseudo C++ code:
int main() {
Object *a = new Object;
Object *b = a;
Object *c = b;
bar(c);
return 0;
}
void bar(Object *tempObj) {
tempObj = new Object;
//changes address of a copy of the ptr arg
cout << std::to_string(*tempObj) << endl;
}
(I know there is no Object
class in C++ and that to_string
isn't defined for every class like it is in Java, but for the sake of example I think it helps illustrate the concept.)
Am I correct? Bottom line: what's going on under the hood? I'd like a more explicit answer.