1

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?

Asad Ganiev
  • 427
  • 4
  • 12
  • 4
    Local variables and parameters are classified separately, but they behave the same way in pretty much all scenarios. Basically you seem to believe that Java uses pass-by-reference semantics, but it doesn't. It uses pass-by-value, always. See https://stackoverflow.com/questions/40480 – Jon Skeet Dec 12 '20 at 09:04
  • 2
    Closed as a duplicate because even though this question isn't specifically *asking* about pass-by-reference vs pass-by-value, that's the cause of the misunderstanding. – Jon Skeet Dec 12 '20 at 09:05
  • Did you try compiling and running this program? – NomadMaker Dec 12 '20 at 09:25
  • @NomadMaker. Sure. the output as I showed `3 2`. – Asad Ganiev Dec 12 '20 at 09:35
  • Same with mine, and the values I got in my head. The explanation from @JonSkeet is correct. One problem with these types of questions: sometimes the given answer is wrong, so it's best to try it yourself if you can. – NomadMaker Dec 12 '20 at 09:40
  • @NomadMaker: I think you may have misread the question. The OP *expected* it to be `2 2`, but that wasn't an answer *given* to them. – Jon Skeet Dec 12 '20 at 10:30

0 Answers0