Last week I had a job interview for Java Developer, interviewer asked me following question:
What would be the output of the this code?
public class B {
public static void main(String[] args) {
A a = new A(3);
m1(a);
System.out.println(a.getV());
m2(a);
System.out.println(a.getV());
}
private static void m1(A a) {
a = new A(2);
}
private static void m2(A a) {
a.setV(2);
}
public static class A {
private int v;
public A(int v) {
this.v = v;
}
void setV(int v) {
this.v = v;
}
int getV() {
return v;
}
}
}
And my answer was that this class will print 2 2
. And I was very surprised that actual printed values would be 3 2
. I was sure that in method m1
the a
will be redefined. Interviewer said that a
will be local variable in this case so that's why the passed argument a
won't be overwritten. In my humble opinion to declare the local variable it should at least look like this: A a = new A(2);
.
I never write this kind of messy code in my day life, but it is made me mad that I didn't know about it. I even searched JLS11, but I couldn't find where it is mentioned.
Could anyone explain me why it is allowed in Java and where it is mentioned?