Search code examples
javaoopmutation

Can I mutate argument in Java?


In C++ I might do something like:

sometype var = somevalue;
mutate(var);
// var is now someothervalue

void mutate(sometype &a) {
    a = someothervalue;
}

Is there an equivalent thing in Java?

I am trying to accomplish something like:

Customer a;

public static void main(String[] args) {
    a = newCustomer("Charles");
    Customer b = null;
    mutate(b);
    System.out.println(b.getName()); // NullPointerException, expected "Charles"
}

void mutate(Customer c) {
    c = a;
}

If Customer is mutable, why does this yield NullPointerException?


Solution

  • Looks like you are confused with Mutability. Mutability is just changing the object state. What you are showing in the example is not just mutability. You are completely changing the instance by referring that to some other instance (=).

    sometype var = somevalue;
    mutate(var);
    
    void mutate(sometype a) {
        a = someothervalue; // changing a to someothervalue.
    }
    

    What mutability is

    sometype var = somevalue;
    mutate(var);
    var.getChangeState() // just gives you the latest value you done in mutate method
    
        void mutate(sometype a) {
            varType someParamForA= valueX;
            a.changeState(someParamForA); // changing a param inside object a.
        }
    

    Yes, in case mutable objects that is completely valid in Java. You can see the changes after you called the mutate method.

    case of primitives ::

    Remember that you cannot do that with Java in case of primitives. All the primitive variables are immutable.

    If you want to acheive the same with Java for primitives, you can try something like this

    int var = 0;
    var = mutate(var);
    
    int mutate(int a) {
        a = a + 1;
        return a;
    }