Edit: I am aware that there are plenty of questions abut pass-by-reference/value and so on, and I've checked a ton of them. I still don't 'get' it. If someone could just explain THIS piece of code like I'm three years old, I think it would finally click.
Edit 2: I'm an idiot. There WAS a main method, I just read over it somehow. Adjusted the example code.
Original post:
I would never play 'reference hide-and-seek' in real life, but I am stumped by the following exam question. I know the answer, but I cannot figure out WHY it is the answer, if that makes any sense. If someone can help me make this 'click', I would greatly appreciate it.
Here is the code:
class Person {
public String name;
public int height;
}
class EJavaGuruPassObjects1 {
public static void main(String args[]) {
Person p = new Person();
p.name = "EJava";
anotherMethod(p);
System.out.println(p.name);
someMethod(p);
System.out.println(p.name);
}
static void anotherMethod(Person p) {
p = new Person();
p.name = "anotherMethod";
System.out.println(p.name);
}
static void someMethod(Person p) {
p.name = "someMethod";
System.out.println(p.name);
}
}
According to the book I'm using, the code should output:
anotherMethod EJava someMethod someMethod
I can't, for the life of me, figure out why it does this?
The third and fourth line of the answer, someMethod has set the name of 'p' to "someMethod" and then it printed p.name. Okay, no problem there. But anotherMethod does something curious: it seems to assign either a new Person object to 'p', or create a new reference variable that is also called 'p' and assigns the new Person object to that one. I suspect it does the latter.
Now it gets interesting: the method has worked its magic and the remaining code wants to print p.name now. If the existing variable was reassigned (I don't think so, but... maybe?), it should print "anotherMethod" again. If a second 'p' variable was indeed created, we have a problem. Why does it print EJava? How does it know which 'p' reference is adressed?