Search code examples
javaparameter-passingnew-operator

Passing object in Java and try to change them in many ways


I know a little bit about how Java is pass by value, and how passing a object to a method can change the object's field (ex. change1() in the Car class).

However, my question is why change2() and change3() don't change anything (especially change3())

public class question {

    public static void main(String[] args)
    {
        Car c1 = new Car(1000,"Hyundai");
        Car c2 = new Car(2000,"BMW");

        c1.change3(c1);
        c1.change3(c2);

        System.out.println(c1.name  + " "+ c1.price );
        System.out.println(c2.name +  " " + c2.price);
    }
}

class Car
{   
    int price;
    String name;

    Car(int p , String n)
    {
        this.price=p;
        this.name=n;
    }

    void change1(Car c)
    {
        c.price=0;
        c.name="Changed";
    }

    void change2(Car c)
    {
        c = new Car(999,"Honda");
    }

    void change3(Car c)
    {
        c = new Car(888,"Audi");
        c.price=80;
        c.name="xxx";
    }   
}

Solution

  • Every time JVM executes new operator, a new Object/Instance is being created. You are creating a new object of the Car type in your change3(Car c) method and storing the reference on that object into local variable c. After this, anything you set on that c is amending new object, and not the one you passed a reference of.

    void change3(Car c) //receives the reference to the object you pass;
    {
        c = new Car(888,"Audi"); //creates a new Car object and assigns reference to that **new object** to the variable c.
        c.price=80; //here, you're changing the price/name fields of different object.
        c.name="xxx";
    }  
    

    Pay attention, that in change1(Car c) you do not create a new object, but in change2(Car c) and change3(Car c) - you do [explicitly] create new objects.