4

I created two objects for the test class where I passed the values 10 and 20 and when I passed second object to the test constructor. It returned me 0 0 instead of 40, 4 as an output. Can anyone explain me why is it happening so?

class Test{
        public int a,b;
        Test(){
                a=-1;
                b=-1;
        }
        Test(int i,int j){
                a=i;
                b=j;
        }
        void mest(Test o){
                o.a*=2;
                o.b=2*2;
        }
        Test(Test ob){
                ob.a*=2;
                ob.b=2*2;
        }
}
public class Main{
        public static void main(String[] args){
                Test t = new Test(10,20);
                System.out.println(t.a +" "+ t.b);// 10, 20
                t.mest(t);      
                System.out.println(t.a +" "+ t.b);// 20, 4
                Test t2 = new Test(t);
                System.out.println(t2.a +" "+ t2.b); // 0 , 0
        }
}
2
  • 1
    You can't pass by reference in Java. You're passing an object reference by value, which isn't the same. Commented Nov 21, 2019 at 11:08
  • I don't understand why you expect the results to be anything else. Can you explain? Commented Nov 21, 2019 at 11:12

2 Answers 2

5

Your Test(Test ob) constructor mutates the instance variables of the instance you pass to it (Test ob), leaving the properties of the newly created instance with default 0 values.

Perhaps you intended to write:

Test(Test ob) {
    this.a = ob.a*2;
    this.b = 2*2;
}
Sign up to request clarification or add additional context in comments.

Comments

3

You change the variables of ob instead of assigning them to this.a and this.b.
You probably want to use this:

Test(Test ob){
        this.a = ob.a*2;
        this.b = 4;
}

You are seeing 0's because the default value of primitive data types is either 0 or false in the case of boolean.

Edit: In any case you shouldn't alter any variables in a copy constructor except for just copying.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.